最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python查詢自己或任意指定的IP地址

 更新時間:2025年10月21日 08:49:44   作者:燭陰  
這篇文章主要為大家詳細介紹了如何使用Python查詢自己或任意指定的IP地址,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下

準備工作:安裝必備工具

首先,請確保你的Python環(huán)境中安裝了requests庫。

pip install requests

第一步:查詢自己的公網(wǎng) IP 信息

import requests
import json

# 向ipinfo.io發(fā)送請求,不帶任何IP地址,它會默認查詢你自己的IP
url = "https://ipinfo.io/json"

try:
    response = requests.get(url)
    response.raise_for_status() # 如果請求失敗 (如狀態(tài)碼 4xx, 5xx), 會拋出異常

    # 將返回的JSON格式數(shù)據(jù)解析為Python字典
    data = response.json()

    print("--- 你的IP信息詳情 ---")
    # 為了美觀,使用json.dumps進行格式化輸出
    print(json.dumps(data, indent=4, ensure_ascii=False))

except requests.exceptions.RequestException as e:
    print(f"請求失敗: {e}")

運行后,你將看到類似這樣的輸出(信息會根據(jù)你的實際情況而變):

{
    "ip": "xxx.xxx.xxx.xxx",
    "hostname": "some.host.name",
    "city": "xx",
    "region": "xx",
    "country": "CN",
    "loc": "39.9042,116.4074",
    "org": "xx",
    "postal": "100000",
    "timezone": "Asia/Shanghai",
    "readme": "https://ipinfo.io/missingauth"
}

第二步:查詢?nèi)我庵付ǖ?IP 地址

我們可以查詢?nèi)魏我粋€我們想查的公網(wǎng)IP,比如谷歌的公共DNS服務器 8.8.8.8

import requests
import json

# 定義要查詢的IP地址
target_ip = "8.8.8.8"

# 構(gòu)造請求URL,將IP地址拼接到URL中
url = f"https://ipinfo.io/{target_ip}/json"

try:
    response = requests.get(url)
    response.raise_for_status()

    data = response.json()

    print(f"--- IP: {target_ip} 的信息詳情 ---")
    print(json.dumps(data, indent=4, ensure_ascii=False))

except requests.exceptions.RequestException as e:
    print(f"請求失敗: {e}")

輸出將會是:

{
    "ip": "8.8.8.8",
    "hostname": "dns.google",
    "city": "Mountain View",
    "region": "California",
    "country": "US",
    "loc": "37.4056,-122.0775",
    "org": "AS15169 Google LLC",
    "postal": "94043",
    "timezone": "America/Los_Angeles",
    "readme": "https://ipinfo.io/missingauth",
    "anycast": true
}

第三步:自由封裝成自己需要的內(nèi)容顯示庫

示例

import requests

def get_ip_info(ip_address: str) -> dict | None:
    """
    查詢指定IP地址的詳細信息。
    
    :param ip_address: 要查詢的IP地址字符串。
    :return: 包含IP信息的字典,如果查詢失敗則返回None。
    """
    url = f"https://ipinfo.io/{ip_address}/json"
    try:
        response = requests.get(url, timeout=5) # 增加超時設置
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"查詢IP {ip_address} 時出錯: {e}")
        return None

# --- 使用我們封裝好的函數(shù) ---
if __name__ == "__main__":
    ip_list = ["8.8.8.8", "1.1.1.1", "114.114.114.114"]
    
    for ip in ip_list:
        info = get_ip_info(ip)
        if info:
            country = info.get('country', 'N/A')
            city = info.get('city', 'N/A')
            org = info.get('org', 'N/A')
            print(f"IP: {ip:<15} | Location: {country}, {city} | Organization: {org}")

方法補充

python 獲取本機IP地址的多種方法

方法一: 通常使用socket.gethostbyname()方法即可獲取本機IP地址,但有時候獲取不到(比如沒有正確設置主機名稱),示例代碼如下:

import socket

# 獲取本機計算機名稱
hostname = socket.gethostname()
# 獲取本機ip
ip = socket.gethostbyname(hostname)
print(ip)

方法二: 親測本方法在windows和Linux系統(tǒng)下均可正確獲取IP地址

import socket

def get_host_ip():
    """
    查詢本機ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip

if __name__ == '__main__':
    print(get_host_ip())

到此這篇關于使用Python查詢自己或任意指定的IP地址的文章就介紹到這了,更多相關Python查詢IP地址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

黔江区| 灌阳县| 麻江县| 永胜县| 南阳市| 鄂州市| 涪陵区| 灵武市| 武隆县| 宁乡县| 远安县| 宜黄县| 阳泉市| 黎城县| 巢湖市| 游戏| 楚雄市| 武功县| 枝江市| 固安县| 凤冈县| 绥中县| 渝北区| 霍林郭勒市| 梁河县| 九龙城区| 麦盖提县| 遂平县| 永登县| 资兴市| 星座| 永泰县| 达日县| 开化县| 雅安市| 崇文区| 宁都县| 武汉市| 惠东县| 东兰县| 新乐市|