几种获取PC网卡ip地址的方法

Zss 发表于:

方法一:通过socket.gethostbyname方法获得

import socket
localIP = socket.gethostbyname(socket.gethostname())#得到本地ip
print "local ip:%s "%localIP

方法二:通过socket.gethostbyname_ex方法获得本机主机名和ip地址列表

import socket
ipList = socket.gethostbyname_ex(socket.gethostname())
print(ipList)

方法三:推荐使用第三种,不通过主机或者网卡名字来获取

from socket import *

def get_host_ip():
    try:
        s = socket(AF_INET,SOCK_DGRAM)
        s.connect(('8.8.8.8', 8887))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

参考:https://blog.csdn.net/weixin_40539892/article/details/79103254