Finding local IP addresses using Python's stdlib

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

    This will work on most linux boxes:

    import socket, subprocess, re
    def get_ipv4_address():
        """
        Returns IP address(es) of current machine.
        :return:
        """
        p = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
        ifc_resp = p.communicate()
        patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        resp = patt.findall(ifc_resp[0])
        print resp
    
    get_ipv4_address()
    

提交回复
热议问题