Python提供了多种方式来获取IP地址。以下是几种常用的方法:
import socket
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print("主机名:", hostname)
print("IP地址:", ip_address)
import requests
response = requests.get("https://api.ipify.org?format=json")
ip_address = response.json()["ip"]
print("IP地址:", ip_address)
import netifaces
interfaces = netifaces.interfaces()
for interface in interfaces:
addresses = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addresses:
ip_address = addresses[netifaces.AF_INET][0]["addr"]
print("接口:", interface)
print("IP地址:", ip_address)
这些方法可以根据不同的需求选择使用。请注意,获取IP地址可能会受到网络环境和权限限制的影响。
领取专属 10元无门槛券
手把手带您无忧上云