Maria
Maria

Reputation: 377

socket error - python

i want to get the local private machine's address, running the following piece of code:

socket.gethostbyaddr(socket.gethostname())

gives the error:

socket.herror: [Errno 2] Host name lookup failure

i know i can see local machine's address, by using

socket.gethostbyname(socket.gethostname())

but it shows the public address of my network (or machine) and ifcofig shows another address for my wlan. can some one help me on this issue? Thanks

Upvotes: 3

Views: 585

Answers (1)

James Mills
James Mills

Reputation: 19050

I believe you're going to find netifaces a little more useful here.

It appears to be a cross-platform library to deal with Network Interfaces.

Example:

>>> from netifaces import interfaces, ifaddresses
>>> interfaces()
['lo', 'sit0', 'enp3s0', 'docker0']
>>> ifaddresses("enp3s0")
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': 'bc:5f:f4:97:5a:69'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': '2001:470:edee:0:be5f:f4ff:fe97:5a69'}, {'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::be5f:f4ff:fe97:5a69%enp3s0'}]}
>>> 
>>> ifaddresses("enp3s0")[2][0]["addr"]
'10.0.0.2'  # <-- My Desktop's LAN IP Address.

Upvotes: 1

Related Questions