1

I was writing a program to assign IP address to beaglebone black in python using ioctl.

(reference How to assign IP address to interface in python? and Getting IP address of the beagleboard using python )

Since IOCTL method implemented in Linux Kernel needs all the parameters to be passed into a particular structure. Hence I constructed all those parameters as a struct and then passed to IOCTL.

bin_ip = socket.inet_aton('192.168.0.1')
ifreq = struct.pack('16sH2s4s8s', 'eth0', socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)

found partial meaning of first argument at https://docs.python.org/3.0/library/struct.html as s= char[] and H = unsigned short what is meaning of numbers 16 2 4 8 written with s and H

edit: For the 's' format character, the count is interpreted as the length of the bytes, for example, 16s means a single 16-byte string followed by 1 unsigned short, 2-byte string ,4-byte string , 8-byte string

why 4th argument is '\x00\x00'and last argument is '\x00\x00\x00\x00\x00\x00\x00\x00'? Is this the standard format / expected format?

Community
  • 1
  • 1

1 Answers1

0

It appears that the struct being packed here is ifreq, where the fields "ifr_name" and "ifr_addr" gets set. 'eth0' gets set for "ifr_name", while the rest is for "ifr_addr".

Ifr_addr is a sockaddr, in this case I suppose actually a sockaddr_in. Based on this page the fields are:

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

In your code socket.AF_INET sets the sin_family. Then the fourth argument two zeroes are the port, likely as here the IP address is set so it isn't port-specific. Then comes the ip address and finally eight zeroes.

Bemmu
  • 17,849
  • 16
  • 76
  • 93