I’m learning socket programming in C & downloaded a simple tcp server source file. I understand every line except the 2nd parameters in these functions:
accept(socket_fd, (struct sockaddr *)&client, &length);
bind(socket_fd, (struct sockaddr *)&server, length);
The accept + bind functions are the typical functions in “sys/types.h” & “sys/socket.h”, and the man page describes it as a pointer to a struct, but I still can’t understand what’s really going on here.
Can someone please explain what is going on in the second parameter? The brackets, pointer and address symbols are confusing me in the same expression.
Thanks in advance!
The
&symbol essentially means “get the address of the value/object”. The(struct sockaddr *)is a cast. It tells the compiler that you want to treat the address as a pointer to a sockaddr structure. So together, it is telling the compiler thatclientcan be treated as a sockaddr structure and to pass the address of it to the function. In the case of theacceptfunction, the address of the connecting socket will be stored in the given structure.