当前位置:   article > 正文

python获取本地公网IP的三种方法_python获取公网ip

python获取公网ip

一、requests模块(python3)

import requests

def get_public_ip():
    response = requests.get('http://ip-api.com/json')
    if response.status_code == 200:
        data = response.json()
        if data['status'] == 'success':
            return data['query']
    return None
print(get_public_ip())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二、urllib模块(python3)

import urllib.request

def get_ip():
    url = "https://api.ipify.org"
    response = urllib.request.urlopen(url)
    return response.read().decode()
print(get_ip())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

三、urllib2模块(Python2)

import urllib2 as request

url = "http://ifconfig.me/ip"
req = request.Request(url=url)
res = request.urlopen(req)
ip = res.read().decode()
print(ip)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/628403
推荐阅读
相关标签
  

闽ICP备14008679号