在Python中获取IP地址可以通过以下几种方法:
1. 使用`socket`库:
import socket
def get_local_ip():
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
return local_ip
def get_public_ip():
try:
response = requests.get('http://httpbin.org/ip')
data = response.json()
ip = data['origin']
return ip
except requests.exceptions.RequestException:
return '获取公网IP失败'
获取本机IP地址
local_ip = get_local_ip()
print('本地IP地址为:', local_ip)
获取公网IP地址
public_ip = get_public_ip()
print('公网IP地址为:', public_ip)
2. 使用第三方库`netifaces`:
import netifaces
def get_local_ip():
for interface in netifaces.interfaces():
addresses = netifaces.ifaddresses(interface)
for address in addresses:
if address['family'] == netifaces.AF_INET and not address['addr'].startswith('127.'):
return address['addr']
return '无法获取本地IP地址'
获取本机IP地址
local_ip = get_local_ip()
print('本地IP地址为:', local_ip)
3. 使用第三方服务API获取公网IP:
import requests
def get_public_ip():
try:
response = requests.get('http://myip.ipip.net')
return response.text.strip()
except requests.exceptions.RequestException:
return '获取公网IP失败'
获取公网IP地址
public_ip = get_public_ip()
print('公网IP地址为:', public_ip)