Is zeroing out the "sockaddr_in" structure necessary?

Viewed 3370

Everywhere I look, I see the following piece of code:

struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = ip;

In C++, the same idea is usually expressed as

sockaddr_in addr = {}; // unneccesary(?) value-initialzation
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = ip;

Yet nowhere I look (in terms of official documentation) do I see any requirement to zero out the structure before setting those members! Yes, usually BSD sockets implementations do have a sin_zero member defined for sockaddr_in, but they always say the member is needed for padding, to align the size of sockaddr_in with sockaddr. And they never request one to put any specific contents into it.

Is there any real, documentation proven need to zero out the struct?

P.S. Before you VTC the question as a duplicate of one of several SO questions regarding memset on sockaddr_in, please make sure the question your are suggesting as a duplicate has any links to official documentation rather than just speculation on 'initializing of unused members just in case'.

2 Answers

A bit late to the party - but here's something relevant, that I think is a worthwhile addition to the discussion. In the 3rd edition of the “Unix Network Programming” of Richard Stevens, on page 70, there's this:

“...when binding non-wildcard IPv4 address, this member must be zero (pp. 731-732 of TCPv2)”

Stevens here mentions "TCPv2" - and the "member" he is talking about is sin_zero. This seems to fit with the profile of your question... at least in the context of bind-ing. Notice that he uses the word must.

Whether this answer qualifies for "official documentation" or not... I leave that up to you! But as others have said, regardless of whether it's official or not... it's for sure a good idea to memset to zero (or use = {0}; at structure variable definition). In this way, you have one less thing to worry about...

Related