Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why memset sockaddr_in to 0

Is there any definitive guide that says we have to initialize the sockaddr_in struct to zero for a particular reason?

// IPv4 AF_INET sockets:
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
};

Whenever I looked in real code or example or books it always has the code structure similar to the following:

struct sockaddr_in foo;
memset(&foo, 0, sizeof(foo)); 
foo.sin_port = htons(1025);
foo.sin_family = AF_INET;
inet_pton(AF_INET, "10.0.0.1", &foo.sin_addr);

I understand that some sources says that the char sin_zero[8] member is there for padding and should be set to zero but why zeroing the rest. Especially when they are initialized in most cases within next few lines of declaration. Even about sin_zero member the beej programming guide said it is not mandatory to zero them out anymore. I have searched for an explanation but nothing to the point turned up. This stack overflow question has some different suggestions on the initialization itself but does not explain why the zeroing is necessary.

Is it a legacy practice or there are some real reason I am missing out? Any reference is appreciated.

like image 457
jazaman Avatar asked Jul 10 '14 01:07

jazaman


People also ask

What does Sockaddr_in mean?

The SOCKADDR_IN structure specifies a transport address and port for the AF_INET address family.

What's the structure of Sockaddr_in?

The “sockaddr_in” structure is very commonly used in socket programming in the C programming language. This structure allows you to bind a socket with the desired address so that a server can listen to the clients' connection requests.


1 Answers

Think of it as a default constructor, i.e. it initializes the data to known values (0 in this case). This can help mitigate issues related to non-initialized data when using PODs, like forgetting to set a member, although memset isn't really necessary and you can just value-initialize the struct with sockaddr_in foo{}; (incidentally this also results in better assembly code behind the scenes as the compiler can movq 0 everything instead of calling memset, not that it'll make much difference in 99% of cases).

If you are absolutely sure you are going to set all members then it isn't strictly necessary, although it can help catch bugs earlier if you forget to initialize something.

like image 59
user657267 Avatar answered Oct 19 '22 22:10

user657267