Finding local IP addresses using Python's stdlib

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

    To get the ip address you can use a shell command directly in python:

    import socket, subprocess
    
    def get_ip_and_hostname():
        hostname =  socket.gethostname()
    
        shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'"
        proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
        (out, err) = proc.communicate()
    
        ip_list = out.split('\n')
        ip = ip_list[0]
    
        for _ip in ip_list:
            try:
                if _ip != "127.0.0.1" and _ip.split(".")[3] != "1":
                    ip = _ip
            except:
                pass
        return ip, hostname
    
    ip_addr, hostname = get_ip_and_hostname()
    

提交回复
热议问题