>>> from socket import socket, SOCK_DGRAM, AF_INET >>> s = socket(AF_INET, SOCK_DGRAM) >>> s.connect(('google.com', 0)) >>> s.getsockname() ('192.168.1.113', 43711) 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.whereismyip.com").read()).group(0)