What is bzero and Why to Use sin_zero for Zero Padding in Socket Server and Client

Spread the love

The question that I have mentioned in the title “What is bzero and Why to use sin zero for zero padding in Socket Server and Client” of the article is related to “Socket Server” in C programming for TCP/IP communication. Those who are from the computer science or engineering background, maybe they used to do this kind of code as their project work. Also software developers who design Socket Server and Socket Cleint, they also know about this topic. But I am not sure how many of them are really clear about the question that I have mentioned in the article title. But this is very important for the beginners to get a clear idea while doing the programming of Socket Server and Socket Client. That is why I am explaining this topic.

To get a clear idea about bzero and sin_zero, we really need to have a clear idea about struct sockaddr_in and struct sockaddr. But before going to inside, the answer of the question is we use bzero to make the size of struct sockaddr_in and struct sockaddr equal. Now the question comes, then what are the structures of this two types of struct. The details is below:

struct sockaddr {
sa_family; //2 bytes
sa_data; // 14 bytes

};

and

struct sockaddr_in{

sin_family; // 2 bytes
sin_port; //2 bytes
sin_addr; // 4 bytes is the IP Address
sin_zero; // 8 bytes in size and provided only to ensure 16 bytes

}

So, from the above details it is clear that we are using sin_zero to put extra 8 bytes of zero to make the size equal to the size of struct sockaddr. As struct sockaddr_in needs to be cast to struct sockaddr, it has to be kept the same size.

Now, the question comes why we need to cast sockaddr_in to sockaddr when calling bind()?

note: bind (sock, (struct sockaddr*)&server, sockaddr_len)

The answer is sockaddr is a descriptor for any kind of socket operation whereas sockaddr_in is a struct specific to IP Based communication. So, while binding we need to cast it with struct sockaddr. I think the above explanation will help you to understand the concept. If you have more question, you can ask me through comments.

5 Responses to “What is bzero and Why to Use sin_zero for Zero Padding in Socket Server and Client”
  1. investasi April 21, 2016
  2. dirsa May 14, 2016
  3. https://twitter.com/ May 15, 2016
    • Himadri Subrah Saha May 16, 2016
  4. grawer w szkle lubin October 24, 2017

Leave a Reply