HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Finding local IP addresses using Python's stdlib

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
addressesstdlibfindingusingpythonlocal

Problem

How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

Solution

import socket
socket.gethostbyname(socket.gethostname())


This won't work always (returns 127.0.0.1 on machines having the hostname in /etc/hosts as 127.0.0.1), a paliative would be what gimel shows, use socket.getfqdn() instead. Of course your machine needs a resolvable hostname.

If you need to get all the ip addresses, you can instead use:
socket.gethostbyname_ex(socket.gethostname())


See the documentation for more information about gethostbyname_ex.

Context

Stack Overflow Q#166506, score: 571

Revisions (0)

No revisions yet.