在Python中查询本机IP地址,可以使用以下几种方法:
1. 使用`socket`模块:
```python
import socket
def get_local_ip():
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
return local_ip
print("本机IP地址为:", get_local_ip())
2. 使用`socket`模块创建UDP连接到外部服务(如Google的DNS服务器8.8.8.8)来获取IP地址:```pythonimport socket
def get_ip_address():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()
s.close()
return ip_address
except socket.error:
return "获取IP地址失败"
print("本机IP地址为:", get_ip_address())

3. 使用第三方库`netifaces`来获取网络接口的IP地址:
```python
import netifaces
def get_ip_address():
for interface in netifaces.interfaces():
addresses = netifaces.ifaddresses(interface)
for address in addresses:
if address['family'] == netifaces.AF_INET and address['addr'] != '127.0.0.1':
return address['addr']
return "无法获取IP地址"
print("本机IP地址为:", get_ip_address())
以上方法可以帮助你获取本机在局域网内的IP地址。如果你需要获取公网IP地址,可以使用如下代码:```pythonimport requests
def get_public_ip():
try:
response = requests.get("https://api.ipify.org", timeout=5)
return response.text
except requests.exceptions.RequestException:
return "无法获取公网IP地址"
print("公网IP地址为:", get_public_ip())
请选择适合你需求的方法进行尝试
