Linux import socket import fcntl import struct def get_ip_address(ifname): 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]) #get_ip_address('lo')环回地址 #get_ip_address('eth0')主机ip地址 windows import re,urllib2 from subprocess import Popen, PIPE print "本机的私网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',Popen('ipconfig', stdout=PIPE).stdout.read()).group(0) print "本机的公网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.7qiao.cn/ip.php").read()).group(0)