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 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(('', 80))
ip, _ = sock.getsockname()


© 2018-2020 Florian Einfalt