简体   繁体   中英

Socket's system call Bind In c

I have been asked in an interview why there is a need of calculating the size of the address to which it is bound in bind system call.

bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr))

Means i would like to know what is purpose of having third argument in bind system call??

Because the sockaddr structure serves more or less as a "base" structure for "derived" structures like sockaddr_in . It's almost an inheritance mechanism.

sockaddr contains variable-length data that can be used by "derived" structures like sockaddr_* , hence you need to precise the effective size of the "derived" structure.

C calls generally need the size of the data that is passed to them as parameters, thats all the struct is doing, otherwise, when reading data from the struct, the internal function could try to read past the bounds of the struct, and we both know that's bad.

It's a check. Type information is not passed to the function so it uses the size to verify that the structure is likely of the correct type, or at least big enough that it's not going to write to out-of-bounds memory.

It is also a form of future-proofing: If a later version of the structure had more fields and forced the structure to grow in size, the receiving call could differentiate between old/new and only fill in the amount of data possible without worry of writing out-of-bounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM