class Getmyip:
def getip(self):
try:
myip = self.visit("http://www.ip138.com/ip2city.asp")
except:
try:
myip = self.visit("http://www.bliao.com/ip.phtml")
except:
try:
myip = self.visit("http://www.whereismyip.com/")
except:
myip = "So sorry!!!"
return myip
def visit(self,url):
opener = urllib2.urlopen(url)
if url == opener.geturl():
str = opener.read()
return re.search('\d+\.\d+\.\d+\.\d+',str).group(0)
getmyip = Getmyip()
localip = getmyip.getip()
print localip二、Linux下获取本地的IP
# -*- coding:UTF-8 -*-
import os
ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read()
ip = ip[ip.find(':')+1:ip.find('\n')]
print ip
本文介绍了一种使用Python实现获取IP地址的方法,包括通过访问特定网站来获取公网IP及在Linux环境下读取本地IP地址的具体代码实现。
4036

被折叠的 条评论
为什么被折叠?



