Why do you clear the socket address structure when making a socket connection?

1. When I read the socket connection, the book will use the memset or bzero function to zero the address structure

bzero (& server_addr,sizeof (server_addr));
server_addr.sin_family = AF_INET;
inet_pton (AF_INET, ip, & server_addr.sin_addr);
server_addr.sin_port = htons (port);

)

but removing the first sentence will have no effect. I want to know what the meaning of this zero is

.

most system call uses struct sockaddr structures instead of structures such as struct sockaddr_in that we use, so we usually cast types when we call system call.

if you look at the structure of struct sockaddr_in, you will find that it has a member of sin_zero, as its name, this member is to zero, the purpose of its existence is to align with the struct sockaddr structure, the length is the same.

some systems may not care whether it is set to zero, but some systems will make judgments, which may cause some undefined behavior. So, for the sake of compatibility, you still need to set zero

.
Menu