socket模块包含了丰富的函数和方法,可以获取主机的ip地址,例如gethostbyname方法可以根据主机名获取ip地址,gethostbyname_ex方法可以获得本机所有ip地址列表,也可以使用netifaces模块获取网卡信息。
- socket.gethostbyname获取
import socket
localIP = socket.gethostbyname(socket.gethostname())#得到本地ip
print "local ip:%s "%localIP
返回结果如下:
172.16.34.102
- socket.gethostbyname_ex获取主机名和ip地址列表
import socket
ipList = socket.gethostbyname_ex(socket.gethostname())
print(ipList)
返回结果如下:
('sharejs.com', [], ['172.16.34.102', '169.254.185.115'])
以上两种方法在linux下也可以使用,linux下还以通过下面的代码获取本机ip地址
import socket
import fcntl
import struct
"""
获取主机ip地址
参数ifname: 通过'lo'获取的为环回地址, 默认获取eth0的主机ip地址
"""
def get_ip_address(ifname='eth0'):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
except:
ips = os.popen("LANG=C ifconfig | grep \"inet addr\" | grep -v \"127.0.0.1\" | awk -F \":\" '{print $2}' | awk '{print $1}'").readlines()
if len(ips) > 0:
return ips[0]
return ''
import netifaces
# 获取网络接口卡的详细信息
def get_interface_details():
interface_details = {
}
for interface in netifaces.interfaces():
interface_info = netifaces.ifaddresses(interface)
interface_details[interface] = interface_info
return interface_details
# 打印网络接口卡的详细信息
interface_details = get_interface_details()
for interface, info in interface_details.items():
print(f"Interface: {interface}")
for address_family, addresses in info.items():
print(f"Address Family: {address_family}")
for address in addresses:
print(f"Address: {address}")