Finding local IP addresses using Python's stdlib

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

    On Linux:

    >>> import socket, struct, fcntl
    >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    >>> sockfd = sock.fileno()
    >>> SIOCGIFADDR = 0x8915
    >>>
    >>> def get_ip(iface = 'eth0'):
    ...     ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
    ...     try:
    ...         res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
    ...     except:
    ...         return None
    ...     ip = struct.unpack('16sH2x4s8x', res)[2]
    ...     return socket.inet_ntoa(ip)
    ... 
    >>> get_ip('eth0')
    '10.80.40.234'
    >>> 
    

提交回复
热议问题