tags:

views:

50

answers:

3

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!

+3  A: 

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 that client can be treated as a sockaddr structure and to pass the address of it to the function. In the case of the accept function, the address of the connecting socket will be stored in the given structure.

Mark Wilkins
+2  A: 

What's happening is that accept and bind function are expecting struct sockaddr pointers, and your client and server variables are probably declared as (struct sockaddr *). So, in order to avoid a warning in C or a compiler error in C++, you need an explicit cast which you do by putting the expression:

(struct sockaddr *)

Before your parameter.

And you need the ampersand, because client and server are not pointers. They were probably declared like:

struct sockaddr_in client, server;
Pablo Santa Cruz
Thank you very much, this is extremely helpful. That is exactly how the structs were declared too.If I declared them as pointers, how would that change the parameters?
Jeremy
ZachS
I think that is easier to understand for me... thanks very much, you've been very helpful.
Jeremy
A: 

It's also worth mentioning that the structures are closely related. Take a look at the picture from Stevens UnP.

Nikolai N Fetissov