获取LAN IP地址
目录
最近在实现一个功能的时候,需要获取本地 LAN 的 IP 地址,查找了一下发现有几种方法可以获取,顺便记录一下……
方法一
import socket
for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
    if not ip.startswith("127."):
        return ip
return None
方法二
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 53))
ip = s.getsockname()[0]
s.close()
return ip
方法三
def get_interface_ip(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
interfaces = ["en0", "en1", "eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0"]
for ifname in interfaces:
    try:
        return get_interface_ip(ifname)
    except Exception as e:
        pass
        
return None
参考:
- http://stackoverflow.com/questions/11735821/python-get-localhost-ip
- http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
 码字很辛苦,转载请注明来自ChenJiehua的《获取LAN IP地址》
 
 
评论