3

I am very new to system programming. I am trying to query some NIC information using Python with ioctl, I easily got the code but having some difficulty in understanding

Python code to get the ip address

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)

Can somebody advice how to decide upon the format and why/how to decide upon number of null characters ?

This link seemed to be almost same question as mine but couldn't find my answer http://www.unix.com/programming/148374-python-struct-pack.html

I found another way of creating ifreq.. ifreq = struct.pack('256s', self.iface). If possible please help me understand the difference.

karthik
  • 305
  • 3
  • 10
  • The structure required is described at [`netdevice(7)`](http://man7.org/linux/man-pages/man7/netdevice.7.html). Presumably, the null byte padding is intended to be the same size as the largest of the items in the `union`. It also appears to be hard-coding the constant `IFNAMSIZ` as 16; I have no idea if that is actually correct. – Kevin Jan 24 '15 at 19:53

0 Answers0