python request 获取当前机器的公网ip

import requests
import traceback

def get_public_ip():
    """
    获取当前机器的公网ip
    """
    try:
        response = requests.get('http://ip-api.com/json')
        if response.status_code == 200:
            data = response.json()
            if data['status'] == 'success':
                return data['query']
    except Exception:
        traceback.print_exc()
    return '127.0.0.1'


ip = get_public_ip()

你可能感兴趣的:(服务器,linux,python)