Finding local IP addresses using Python's stdlib

后端 未结 30 3142
北恋
北恋 2020-11-21 23:54

How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 00:38

    If you're looking for an IPV4 address different from your localhost IP address 127.0.0.1, here is a neat piece of python codes:

    import subprocess
    address = subprocess.check_output(['hostname', '-s', '-I'])
    address = address.decode('utf-8') 
    address=address[:-1]
    

    Which can also be written in a single line:

    address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]
    

    Even if you put localhost in /etc/hostname, the code will still give your local IP address.

提交回复
热议问题