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())

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()))"'


Ferran Jovell