问:何为公网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代码实现,灵活性比较大,另附上Shell命令行获取的三种方式,也比较简单:
curl -s http://ifconfig.me curl -s http://ip.chinaz.com/getip.aspx curl -s http://ipv4.icanhazip.com/
- 微信扫码赞助
- 支付宝赞助
2016/09/18 11:41:35
第一个赞是谁赞的,哈哈