Python打印本机IP
两行代码:
1 import socket 2 print socket.gethostbyname(socket.gethostname())
上面这个东西只能在windows上使用,估计下面这个方法到处都能用:
#!/usr/bin/env python import socket def getip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('www.baidu.com', 0)) ip=s.getsockname()[0] except: ip="" finally: s.close() return ip if __name__=='__main__': print getip()
上面这个方法出自:http://www.cnblogs.com/feisky/archive/2011/11/26/2264306.html
还找到一个用于获取外网IP的方法:
1 import re,urllib2 2 class Getmyip: 3 def getip(self): 4 try: 5 myip = self.visit("http://www.ip138.com/ip2city.asp") 6 except: 7 try: 8 myip = self.visit("http://www.bliao.com/ip.phtml") 9 except: 10 try: 11 myip = self.visit("http://www.whereismyip.com/") 12 except: 13 myip = "So sorry!!!" 14 return myip 15 def visit(self,url): 16 opener = urllib2.urlopen(url) 17 if url == opener.geturl(): 18 str = opener.read() 19 return re.search('\d+\.\d+\.\d+\.\d+',str).group(0) 20 getmyip = Getmyip() 21 localip = getmyip.getip() 22 print localip
出处在这里:http://bbs.bccn.net/thread-298418-1-1.html