3

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

3
  • did you import socket?? Commented May 22, 2014 at 12:58
  • 2
    @ruddra if she didn't, that would result in a totally different error (NameError), that doesn't seem to be the issue here. Commented May 22, 2014 at 13:00
  • yes i did import socket and installed nscd Commented May 22, 2014 at 13:43

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

tnx that worked fine and was what i wanted, but is there a way to find the IP address using sockets?
No not really. Not in the way you describe. The sockets modules only provides the two functions you've already seen and they're limited at best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.