pythonipv4

python get ipv4 from default interface


I'm looking for code but can't find what I'm looking for exactly.

I want to obtain the ipv4 of all the interfaces of the pc.

any idea?

Thank you in advance!


Solution

  • Not guaranteed to work, depends on system configuration. But you can try this for the default interface:

    import socket
    print(socket.gethostbyname(socket.gethostname())) # IP in string, e.g. '192.168.1.123'
    

    If you want to enumerate all interfaces, likely that would be system dependent (e.g. Windows vs Linux), see for example here for a Python 2 code, or you can simply parse the output from system command ifconfig.