Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address from python [duplicate]

I'm trying to get the ip address associated with network interface without spawning additional processes in Linux:

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(), 0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15].encode('utf-8'))
        )[20:24])

But always getting this error:

struct.pack('256s', ifname[:15].encode('utf-8'))
OSError: [Errno 99] Cannot assign requested address

How can I solve this?

like image 715
lichb0rn Avatar asked Feb 04 '18 09:02

lichb0rn


People also ask

How do I find duplicate IP addresses?

Here is how you can check it: On an unaffected host on the same network, open up a command prompt. On a Windows machine, type "arp -a [suspected duplicate IP]" and hit enter. On a Mac or Linux machine, type "arp [suspected duplicate IP]" and hit enter.

Can IP address be duplicate?

If you defined a static IP address for a network device, duplicate IP address conflicts may occur on a DHCP network. See more details. To resolve it, convert the network device with the static IP address to a DHCP client. Or, you can exclude the static IP address from the DHCP scope on the DHCP server.


1 Answers

Translate host to ip :

import socket
print (socket.gethostbyname(socket.gethostname()))

To get host by name :

import socket
print (socket.gethostbyname("www.goole.com"))
like image 151
An0n Avatar answered Sep 25 '22 09:09

An0n