1 #!/usr/bin/python 2 import socket 3 import fcntl 4 import struct 5 def get_ip_address(ifname): 6 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 7 return socket.inet_ntoa(fcntl.ioctl( 8 s.fileno(), 9 0x8915, # SIOCGIFADDR 10 struct.pack('256s',ifname[:15]) 11 )[20:24]) 12 #get_ip_address('lo')环回地址 13 #get_ip_address('eth0')主机ip地址