通過socket.gethostbyname(socket.gethostname())的方式只能獲取到自環網地址127.0.0.1,要獲取到其他網卡(如eth0)ip地址,需通過ioctl實現:
import socket
import fcntl
import struct
def getip(ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
netaddr = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15].encode('utf-8')))
ipaddr = socket.inet_ntoa(netaddr[20:24])
return ipaddr
except OSError as oe:
print ('No such device: ', ifname)
print ('lo: ', getip('lo'))
print ('eth0: ', getip('eth0'))
print ('eth1: ', getip('eth1'))