Why do you have to pass sizeof in socket functions?

c, sockets

Solution

Because it gives a simple simple way to handle many different types of protocols with the same API.

Since a socket can use many different underlying protocols (as pointed out by @larsman), the call can't know which type of structure it's being handed, exactly. There's some basic "inheritance" going on with the various `struct sockaddr` types.

Also, it provides some forward compatibility; it's possible that a binary compiled against one version of the library is run against a later version, in which the address type might have grown (for instance to support IPv6).

By passing the caller's idea of the size to the called function, the called function can take care not to overwrite memory.

Problem

I'm looking into socket programming in C and I'm curious why do you have to pass a parameter and a length of that parameter in functions like `bind()` and `connect()`? Why not just use `sizeof()` inside of the function?

Original source