python–获取公网IP地址

问:何为公网IP地址?

答:即互联网中唯一的,且能被全球互联网(鄙视下GFW)访问的网络地址。

新建文件get_public_ip.py,内容如下:

#!/usr/bin/env python
import re,urllib2
class Get_public_ip:
    def getip(self):
        try:
            myip = self.visit("http://ip.chinaz.com/getip.aspx")
        except:
            try:
                myip = self.visit("http://ipv4.icanhazip.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)
if __name__ == "__main__":
    getmyip = Get_public_ip()
    print getmyip.getip()

运行结果如下:

get_public_ip.png

python代码实现,灵活性比较大,另附上Shell命令行获取的三种方式,也比较简单:

curl -s http://ifconfig.me
curl -s http://ip.chinaz.com/getip.aspx
curl -s http://ipv4.icanhazip.com/

1人评论了“python–获取公网IP地址”

发表评论

滚动至顶部