0

I just got asked this question and couldn't answer it, I looked at how I've been coding it and was really confused. This is how I have been programming the accept() call in a server:

struct sockaddr_in client;

size=sizeof(client);
if(( nds=accept(ds,(struct sockaddr*)&client,&size)) <0)
{
perror("accept");
close(ds);
exit(-1);
}

Where ds is socket descriptor

I know the second parameter of accept is a pointer to the struct but don't know why it should be empty.

davigzzz
  • 134
  • 1
  • 12
  • 5
    It will be filled in by `accept`. It is _either a null pointer, or a pointer to a sockaddr structure where the address of the connecting socket shall be returned._ – 001 Apr 04 '18 at 17:48

1 Answers1

3

Weel, it is an output parameter, you can send it or not, but when you send it, it will be filled with the the connecting socket.

Take a look here http://pubs.opengroup.org/onlinepubs/009695399/functions/accept.html

If address is not a null pointer, the address of the peer for the accepted connection shall be stored in the sockaddr structure pointed to by address, and the length of this address shall be stored in the object pointed to by address_len.

  • 1
    To elaborate, it's like making a phone call. If you make a call, you need to know the other party's phone number. To receive a call, you just pick up the phone. – user3344003 Apr 04 '18 at 22:05
  • And if you want to know the caller's phone number, you look at the caller ID. But you don't have to if you don't want to. Same with `accept()`. The output `sockaddr` is like the caller ID. And if you do use it, you don't have to use `getpeername()` separately to get it – Remy Lebeau Apr 05 '18 at 17:55