Python腳本實(shí)現(xiàn)獲取IP地址
一、腳本功能
1.獲取主機(jī)名
2.獲取外網(wǎng)IP(通過多個(gè)公共API嘗試) IPV4和IPV6
3.獲取所有網(wǎng)絡(luò)接口的內(nèi)網(wǎng)IP
4.保存至文件并打印信息
輸出示例:
主機(jī)名: MyComputer
內(nèi)網(wǎng)IPv4地址:
- 192.168.1.100
- 192.168.56.1
內(nèi)網(wǎng)IPv6地址:
- 2001:0db8:85a3:0000:0000:8a2e:0370:7334
外網(wǎng)IPv4: 203.0.113.1
外網(wǎng)IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
二、注意事項(xiàng)
1.獲取外網(wǎng)IP需要網(wǎng)絡(luò)連接
2.某些網(wǎng)絡(luò)環(huán)境可能會阻止訪問IP查詢服務(wù)
3.如果在代理或VPN環(huán)境下,獲取的外網(wǎng)IP可能是代理或VPN的IP
4.內(nèi)網(wǎng)IP可能會有多個(gè),特別是在有多個(gè)網(wǎng)絡(luò)接口的情況下
5.考慮暫時(shí)關(guān)閉防火墻
6.如果你的網(wǎng)絡(luò)不支持 IPv6,那么相關(guān)的 IPv6 地址將顯示為"無法獲取"
7.某些系統(tǒng)可能需要管理員權(quán)限才能獲取完整的網(wǎng)絡(luò)接口信息
三、準(zhǔn)備工作
導(dǎo)入庫:
import socket import requests import json import time from datetime import datetime
四、完整代碼
import socket
import requests
import json
import time
from datetime import datetime
def get_external_ipv4():
"""獲取外網(wǎng)IPv4地址"""
apis = [
{
'url': 'https://api.ipify.org?format=json',
'timeout': 5,
'headers': {'User-Agent': 'Mozilla/5.0'},
'json': True,
'key': 'ip'
},
{
'url': 'https://api4.ipify.org?format=json',
'timeout': 5,
'headers': {'User-Agent': 'Mozilla/5.0'},
'json': True,
'key': 'ip'
},
{
'url': 'https://ipv4.icanhazip.com',
'timeout': 5,
'headers': {'User-Agent': 'curl/7.64.1'}
}
]
for api in apis:
try:
print(f"嘗試從 {api['url']} 獲取外網(wǎng)IPv4...")
response = requests.get(
url=api['url'],
timeout=api['timeout'],
headers=api['headers']
)
if response.status_code == 200:
if api.get('json'):
data = response.json()
return data[api['key']]
else:
return response.text.strip()
except Exception as e:
print(f"當(dāng)前接口請求失敗: {str(e)}")
continue
return "無法獲取IPv4地址"
def get_external_ipv6():
"""獲取外網(wǎng)IPv6地址"""
apis = [
{
'url': 'https://api6.ipify.org?format=json',
'timeout': 5,
'headers': {'User-Agent': 'Mozilla/5.0'},
'json': True,
'key': 'ip'
},
{
'url': 'https://ipv6.icanhazip.com',
'timeout': 5,
'headers': {'User-Agent': 'curl/7.64.1'}
}
]
for api in apis:
try:
print(f"嘗試從 {api['url']} 獲取外網(wǎng)IPv6...")
response = requests.get(
url=api['url'],
timeout=api['timeout'],
headers=api['headers']
)
if response.status_code == 200:
if api.get('json'):
data = response.json()
return data[api['key']]
else:
return response.text.strip()
except Exception as e:
print(f"當(dāng)前接口請求失敗: {str(e)}")
continue
return "無法獲取IPv6地址"
def get_internal_ips():
"""獲取內(nèi)網(wǎng)IP地址(同時(shí)獲取IPv4和IPv6)"""
internal_ips = {'ipv4': [], 'ipv6': []}
try:
# 獲取所有網(wǎng)絡(luò)接口的所有IP
hostname = socket.gethostname()
addrs = socket.getaddrinfo(hostname, None)
for addr in addrs:
ip = addr[4][0]
# 判斷是否為IPv6地址
if ':' in ip:
if not ip.startswith('fe80:') and not ip.startswith('::1'):
if ip not in internal_ips['ipv6']:
internal_ips['ipv6'].append(ip)
else:
if not ip.startswith('127.'):
if ip not in internal_ips['ipv4']:
internal_ips['ipv4'].append(ip)
# 使用備用方法獲取IPv4
if not internal_ips['ipv4']:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
if ip not in internal_ips['ipv4']:
internal_ips['ipv4'].append(ip)
except:
pass
except Exception as e:
print(f"獲取內(nèi)網(wǎng)IP出錯(cuò): {str(e)}")
return internal_ips
def save_to_file(data):
"""保存信息到文件"""
try:
with open('../辦公與多媒體/ip_info.txt', 'a', encoding='utf-8') as f:
f.write(f"\n{'=' * 50}\n")
f.write(f"檢測時(shí)間: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"主機(jī)名: {data['hostname']}\n\n")
f.write("內(nèi)網(wǎng)IPv4地址:\n")
for ip in data['internal_ipv4']:
f.write(f" - {ip}\n")
f.write("\n內(nèi)網(wǎng)IPv6地址:\n")
for ip in data['internal_ipv6']:
f.write(f" - {ip}\n")
f.write(f"\n外網(wǎng)IPv4: {data['external_ipv4']}\n")
f.write(f"外網(wǎng)IPv6: {data['external_ipv6']}\n")
f.write(f"{'=' * 50}\n")
except Exception as e:
print(f"保存文件時(shí)出錯(cuò): {str(e)}")
def main():
try:
print("開始獲取網(wǎng)絡(luò)信息...\n")
# 獲取主機(jī)名
hostname = socket.gethostname()
print(f"主機(jī)名: {hostname}\n")
# 獲取內(nèi)網(wǎng)IP
internal_ips = get_internal_ips()
print("內(nèi)網(wǎng)IPv4地址:")
for ip in internal_ips['ipv4']:
print(f" - {ip}")
print("\n內(nèi)網(wǎng)IPv6地址:")
for ip in internal_ips['ipv6']:
print(f" - {ip}")
# 獲取外網(wǎng)IP
print("\n正在獲取外網(wǎng)IP...")
external_ipv4 = get_external_ipv4()
external_ipv6 = get_external_ipv6()
print(f"\n外網(wǎng)IPv4: {external_ipv4}")
print(f"外網(wǎng)IPv6: {external_ipv6}")
# 保存信息到文件
data = {
'hostname': hostname,
'internal_ipv4': internal_ips['ipv4'],
'internal_ipv6': internal_ips['ipv6'],
'external_ipv4': external_ipv4,
'external_ipv6': external_ipv6
}
save_to_file(data)
print("\n信息已保存到 ip_info.txt 文件")
except Exception as e:
print(f"程序執(zhí)行出錯(cuò): {str(e)}")
if __name__ == "__main__":
# 確保已安裝requests庫
# pip install requests
main()
# 等待用戶按鍵退出
input("\n按回車鍵退出...")以上就是Python腳本實(shí)現(xiàn)獲取IP地址的詳細(xì)內(nèi)容,更多關(guān)于Python獲取IP地址的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python圖片文字識別與提取實(shí)戰(zhàn)記錄
這篇文章主要介紹了Python圖片文字識別與提取的相關(guān)資料,本文介紹了如何安裝和配置OCR環(huán)境,包括安裝pytesseract擴(kuò)展包、窗口配套軟件以及配置環(huán)境變量,在完成環(huán)境搭建后,即可進(jìn)行圖片中文字的提取,需要的朋友可以參考下2024-09-09
使用pyplot.matshow()函數(shù)添加繪圖標(biāo)題
這篇文章主要介紹了使用pyplot.matshow()函數(shù)添加繪圖標(biāo)題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python transpose()處理高維度數(shù)組的軸變換的實(shí)現(xiàn)
本文主要介紹了python transpose()處理高維度數(shù)組的軸變換的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09
Pytorch中Tensor與各種圖像格式的相互轉(zhuǎn)化詳解
這篇文章主要介紹了Pytorch中Tensor與各種圖像格式的相互轉(zhuǎn)化詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

