python socket编程根据接口获取ip方法
时间: 2023-10-08 22:11:42 浏览: 46
你可以使用 Python 的 `socket` 模块中的 `getaddrinfo()` 函数和 `gethostname()` 函数来获取指定接口的 IP 地址。下面是一个示例代码:
```python
import socket
def get_ip_by_interface(interface_name):
hostname = socket.gethostname()
result = socket.getaddrinfo(hostname, None, socket.AF_INET, socket.SOCK_DGRAM)
for item in result:
ip = item[4][0]
if interface_name in item[3]:
return ip
return None
# 示例
interface_name = 'eth0'
ip = get_ip_by_interface(interface_name)
if ip:
print(f"IP address for interface {interface_name}: {ip}")
else:
print(f"No IP address found for interface {interface_name}")
```
在上面的示例中,`get_ip_by_interface()` 函数接收一个接口名,然后使用 `getaddrinfo()` 函数和 `gethostname()` 函数来获取本机的所有 IPv4 地址。接着,它遍历结果列表,找到包含指定接口名的结果项,然后返回该项对应的 IP 地址。在上面的示例中,我们以 `eth0` 接口为例进行了演示。