有一种socket方法可以获取给定网络接口的IP:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
Run Code Online (Sandbox Code Playgroud)
返回以下内容:
>>> get_ip_address('lo')
'127.0.0.1'
>>> get_ip_address('eth0')
'38.113.228.130'
Run Code Online (Sandbox Code Playgroud)
是否有类似的方法来返回该接口的网络传输?我知道我可以阅读,/proc/net/dev但我喜欢套接字方法.