python ioctl创建ifreq stru

2024-06-26 12:48:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对系统编程很陌生。我试图用Python和ioctl查询一些NIC信息,我很容易得到代码,但在理解上有一些困难

获取ip地址的Python代码

nic = "eth1"
# Create socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# **How did they conclude the formate to be 16sH14s and why 14 times \x00 ? Please advice**
ifreq = struct.pack('16sH14s', nic, socket.AF_INET, '\x00'*14)
result = fcntl.ioctl(fd, SIOCGIFADDR, ifreq)

# My wild guess **unpack format would be same as pack**. But I am wrong
ip = struct.unpack('16sH2x4s8x', result)[2]
print socket.inet_ntoa(ip)

有人能建议如何决定格式,为什么/如何决定空字符的数量?在

这个链接似乎和我的问题几乎一样,但找不到我的答案 http://www.unix.com/programming/148374-python-struct-pack.html

我找到了另一种创建ifreq的方法。。条件=结构包('256s',自我感觉). 如果可能的话,请帮助我理解两者的区别。在


Tags: 代码ip编程socketberesultstructpack