Bitesize: socket.getsockname

August 23, 2018 by Florian Einfalt

Whilst looking at some old code of mine, I discovered a quick way to programmatically retrieve a hosts local IP address, the socket.getsockname() function.

To get the local IP address, create a UDP socket (see socket.SOCK_DGRAM below), connect to an arbitrary server (this can be local or remote, such as google.com) and run the getsockname() function on the socket.

This returns a tuple and the first item in that tuple is the hosts local IP address. Easy.

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(('google.com', 80))
ip, _ = sock.getsockname()
sock.close()
print(ip)

# 192.168.1.2

© 2018-2020 Florian Einfalt