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

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

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

準(zhǔn)備工作:安裝必備工具

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

pip install requests

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

import requests
import json

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

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

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

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

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

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

{
    "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)魏我粋€(gè)我們想查的公網(wǎng)IP,比如谷歌的公共DNS服務(wù)器 8.8.8.8

import requests
import json

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

# 構(gòu)造請(qǐng)求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"請(qǐng)求失敗: {e}")

輸出將會(huì)是:

{
    "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地址的詳細(xì)信息。
    
    :param ip_address: 要查詢的IP地址字符串。
    :return: 包含IP信息的字典,如果查詢失敗則返回None。
    """
    url = f"https://ipinfo.io/{ip_address}/json"
    try:
        response = requests.get(url, timeout=5) # 增加超時(shí)設(shè)置
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"查詢IP {ip_address} 時(shí)出錯(cuò): {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}")

方法補(bǔ)充

python 獲取本機(jī)IP地址的多種方法

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

import socket

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

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

import socket

def get_host_ip():
    """
    查詢本機(jī)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())

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

相關(guān)文章

最新評(píng)論

连平县| 雷州市| 瑞昌市| 龙井市| 镇远县| 宁城县| 徐水县| 焉耆| 临朐县| 南京市| 密云县| 定州市| 腾冲县| 胶南市| 平湖市| 平南县| 孙吴县| 珠海市| 永康市| 石家庄市| 大宁县| 兴文县| 合阳县| 公主岭市| 于都县| 和田县| 托里县| 桃园市| 杂多县| 大埔区| 湟源县| 靖边县| 道孚县| 刚察县| 秭归县| 义乌市| 耿马| 阳泉市| 辽阳市| 五大连池市| 堆龙德庆县|