tags:

views:

54

answers:

5

Can anybody explain me this piece of code?

/* Pad to size of `struct sockaddr'.  */
unsigned char sin_zero[sizeof (struct sockaddr) -
                       __SOCKADDR_COMMON_SIZE -
                       sizeof (in_port_t) -
                       sizeof (struct in_addr)];

here sin_zero is a char array but what is remaining part? It should be some integer. what this sign "-" means? Can anybody explain this to me?

A: 

Sockaddr contains some things like in_addr and in_port_t, and it has room for some more. The sin_zero is the remaining size in sockaddr. It is the size of sockaddr which is not filled with something else.

Supposedly the sin_zero variable would be initialised to all null bytes, and set as the last field or at the end of the sockaddr struct. The purpose of this is to set the remaining bytes to null.

Sjoerd
A: 

sin_zeor is a char array with the size calculated with the formula in the [] brackets The '-' sign is actually a mathematical minus sign :-)

hth

Mario

Mario The Spoon
A: 

It calculates the size of the array based on the size of some structs and a constant. The sign "-" means minus.

dark_charlie
+4  A: 

Well, the - is called a "minus" :-) Seriously, everything between the square brackets is meant to calculate the size of sin_zero, which is a so-called padding. It's a member inside struct sockaddr_in, and it's just here to make sure that struct sockaddr_in is exactly of a certain size, most likely 16 bytes. The idea is to ensure that all struct sockaddr variants are of the same size to avoid malloc problems.

Quoting a document I found on the subject:

The POSIX specification requires only three members in the structure: sin_family, sin_addr, and sin_port. It is acceptable for a POSIX-compliant implementation to define additional structure members, and this is normal for an Internet socket address structure. Almost all implementations add the sin_zero member so that all socket address structures are at least 16 bytes in size.

DarkDust
Thanks buddy. The document is very useful.
+2  A: 

sin_zero is a structure member that is used to pad out the structure to a certain minimum size. In this case, the amount of padding is calculated by starting with the desired size (sizeof (struct sockaddr)) and subtracting the space taken up by the other struct members from it.

So, to answer the question: The sign "-" here just means "subtraction".

Bart van Ingen Schenau