So I'm trying to get the LAN IP Address of the machine the program is running on and compare it to IP Addresses passed to it via UDP.
However when I use:
print str(socket.gethostbyname(socket.gethostname()))
It returns 127.0.0.1 which should be 192.168.1.9.
I've looked through the linux machine and its getting the IP Address of the lo (loopBack) port? I don't know exactly what that is but it should be getting the IP Address of eth0.
I've found that I can subprocess the bash command "ifconfig eth0" but that returns a big block of a string. I can process it down to what I need, but this is going to be running around 3 times a second on a beaglebone so I'd like it to be a little more effecient.
Is there a more elegant way of doing this?
Can I just change the target of gethostname?
Why is it targeting the lo port?
Thanks for your help maners.
Try returning the fully qualified domain name of the machine:
print str(socket.gethostbyname(socket.getfqdn()))
/etc/hosts
probably has an entry resolving hostname to 127.0.0.1
, which is why socket.gethostbyname()
doesn't return what you expect.
Original question asked and answered here, but the socket.getfqdn()
solution didn't stick out at a quick glance. Here's the solution for parsing ifconfig
output if you decide to go that route. Standard library seems more than sufficient for solving your problem.
netifaces seems like a pretty sweet python module which should do the trick for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With