获取自己的公网IP地址

python 获取自己的公网IP地址

要获取你的公网 IP 地址,你可以使用一个 HTTP 请求来查询外部的 IP 地址服务

import requests

def get_public_ip():
    try:
        response = requests.get('https://api.ipify.org')
        if response.status_code == 200:
            return response.text
        else:
            print("Failed to retrieve public IP:", response.status_code)
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    public_ip = get_public_ip()
    if public_ip:
        print("Your public IP address is:", public_ip)

Last updated