python–获取公网IP地址

2016/09/1811:30:47 1

问:何为公网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/
  • 微信扫码赞助
  • weinxin
  • 支付宝赞助
  • weinxin

发表评论

您必须才能发表评论!

目前评论:1   其中:访客  0   博主  0

    • 聆听

      第一个赞是谁赞的,哈哈