Get Current Host's Local Ip

Published on June 24, 2023 | Tags: python networking TIL

Sometimes, when working in a private network, it can be useful to know the current host IP address. If you are in the Linux shell, it can be as easy as using ifconfig and get it from there. However, if you need it in your application or in a script or in a programatic way, it's better to use the socket module from the standard library.


>>> import socket
>>> socket.gethostbyname(socket.gethostname())
'192.168.1.17''

So now is trivial to put this in an alias for easy access:


alias local-ip='python -c "import socket; print(socket.gethostbyname(socket.gethostname()))"'

Ref.: https://docs.python.org/3/library/socket.html#socket.gethostbyname


Ferran Jovell