1. The direction matters

When you call a socket function, you often pass a pointer to a socket address structure. However, how you pass the length of that structure depends on which direction the information is flowing.

A. From process to kernel (Input)

When your program needs to tell the kernel a specific address (e.g., “Connect to this IP” or “Bind to this port”), you pass the structure and its size as a simple integer.

  • Functions: bind, connect, sendto.
  • The Length Argument: You pass the sizeof the structure directly as an integer value.
  • What Happens: The kernel reads exactly that many bytes from your structure. It does not need to change the size, so it doesn’t need a pointer to the size variable.
B. From kernel to process (Output)

When the kernel needs to tell your program an address (e.g., “Who just connected to me?” or “Where did this packet come from?”), the rules change. This is where the Value-Result concept applies.

  • Functions: accept, recvfrom, getsockname, getpeername.
  • The Length Argument: You pass a pointer to an integer variable (e.g., &len).
  • How it Works:
    1. Value (Input): Before calling the function, you set this integer to the size of your buffer (e.g., sizeof(struct sockaddr_in)). This tells the kernel: “I have allocated 16 bytes for you to write into. Don’t write more than that.”
    2. Result (Output): When the function returns, the kernel updates this integer with the actual number of bytes it wrote. This tells you: “I actually only used 16 bytes.”