Finding local IP addresses using Python's stdlib

后端 未结 30 2614
北恋
北恋 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:24

    FYI I can verify that the method:

    import socket
    addr = socket.gethostbyname(socket.gethostname())
    

    Works in OS X (10.6,10.5), Windows XP, and on a well administered RHEL department server. It did not work on a very minimal CentOS VM that I just do some kernel hacking on. So for that instance you can just check for a 127.0.0.1 address and in that case do the following:

    if addr == "127.0.0.1":
         import commands
         output = commands.getoutput("/sbin/ifconfig")
         addr = parseaddress(output)
    

    And then parse the ip address from the output. It should be noted that ifconfig is not in a normal user's PATH by default and that is why I give the full path in the command. I hope this helps.

提交回复
热议问题