商务合作加Q:411239339

python–获取公网IP地址

浏览:583次阅读
一条评论

共计 808 个字符,预计需要花费 3 分钟才能阅读完成。

问:何为公网 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()

运行结果如下:

python-- 获取公网 IP 地址

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

curl -s http://ifconfig.me
curl -s http://ip.chinaz.com/getip.aspx
curl -s http://ipv4.icanhazip.com/
正文完
扫码赞助
post-qrcode
 0
果子
版权声明:本站原创文章,由 果子 于2016-09-18发表,共计808字。
转载说明:除特殊说明外本站文章皆由果较瘦原创发布,转载请注明出处。
评论(一条评论)
2016-09-18 11:41:35 回复

第一个赞是谁赞的,哈哈

 Windows  Chrome  中国广西桂林市电信