Python Forum
Getting IP address - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Getting IP address (/thread-13576.html)



Getting IP address - MuntyScruntfundle - Oct-21-2018

How, I hope this can be a complicated issue, but please assume my device has one ip adapter, one address, no layers of oranges to peel away etc!

The very documented way to get the local IP address is socket.gethostbyname(socket.gethostname())

This is all I've done with sockets before, and as I've always mostly been working on the same node I haven't noticed that this has been returning 127.0.0.1

This is ok when I'm connecting sockets on the same machine, but it ISN'T the local IP address. I need the IP address of the connected adapter.

Now, I fibbed a little earlier, this device has a wifi and hardware port, one will lock out the other, so I need the address of the one that's connected. This will ALLways be cable, unless it's not!

I don't to parse if unless I really have to.

Ideas?

Many thanks.


RE: Getting IP address - wavic - Oct-22-2018

https://nmap.org/


RE: Getting IP address - Gribouillis - Oct-22-2018

Try this perhaps
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('w3.org', 80)) # or python-forum.io or perhaps a known address in your local network
ip = s.getsockname()[0]