get_public_ipaddr.py 691 B

12345678910111213141516171819202122232425262728
  1. #!/usr/bin/env python
  2. import sys,re,socket
  3. if sys.version_info[0] == 2:
  4. import urllib2 as request
  5. else:
  6. import urllib.request as request
  7. class Get_public_ip:
  8. socket.setdefaulttimeout(5)
  9. def getip(self):
  10. try:
  11. myip = self.visit("http://ipv4.icanhazip.com/")
  12. except:
  13. try:
  14. myip = self.visit("http://pv.sohu.com/cityjson?ie=utf-8")
  15. except:
  16. myip = "So sorry!!!"
  17. return myip
  18. def visit(self,url):
  19. opener = request.urlopen(url)
  20. if url == opener.geturl():
  21. str = opener.read().decode('utf-8')
  22. return re.search('\d+\.\d+\.\d+\.\d+',str).group(0)
  23. if __name__ == "__main__":
  24. getmyip = Get_public_ip()
  25. print(getmyip.getip())