Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Getting LAN IP Address of Machine on Ubuntu [duplicate]

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.

like image 962
Poodimizer Avatar asked Mar 13 '13 17:03

Poodimizer


2 Answers

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.

like image 85
Bryan Avatar answered Oct 25 '22 01:10

Bryan


netifaces seems like a pretty sweet python module which should do the trick for you.

like image 29
minism Avatar answered Oct 25 '22 03:10

minism