Using accept(2) method in Linux

Hi everyone,

I'm attempting to create a client-server application. However, an exception keeps being thrown whenever accept() is called. Here's the code segment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Open socket
	char* service = "4000";	// 4000 Portnumber
	m_sock = passiveTCPsock(service, 32);   // passiveTCPsock always returns 4 for some reason
	// Handle Incoming requests
	pthread_t th; pthread_attr_t ta;
	pthread_attr_init(&ta);
	pthread_attr_setdetachstate(&ta, PTHREAD_CREATE_DETACHED);
	for ( ; ; ) {
		int s_sock = accept(m_sock,(struct sockaddr*)&fsin, (socklen_t *)sizeof(fsin));
		if (s_sock < 0)	{
			if (errno == EINTR) continue;
			else { 
			throw ErrorMessage( "Main: Accept Failed" );
			continue;
			}
		}
Where "fsin" is a "struct sockaddr_in", declared above the code segment.

Apparently, since the ErrorMessage was thrown, s_sock must be a negative number. But I passed the same portnumber and "localhost" as parameters to the Client program, so I am not sure what else could be the issue.
Last edited on
accept() returns a socket for the new connection. It also returns the address of the connection.

If the case of TCP, you know in advance (apriori) that the address type is a sockaddr_in. So how does accept know that you passed it a sockaddr_in and not some other kind of address? It knows by the size that you pass in. It also returns the size of the structure it used. And it does all this in the same parameter. So your code should look like:
1
2
3
4
5
6
7
for (;;)
{
    struct sockaddr_in clientaddr;
    socklen_t clientaddr_sz = sizeof(clientaddr);
    int clientsock = accept(serversock, (struct sockaddr*)&clientaddr, &clientaddr_sz);
    // ...
}
That worked. Thank you, but I am confused as to where I went wrong. We handled the first two arguments identically (except for naming). The only difference in our third arguments, aside from naming, is you performed sizeof() before passing in the argument instead of simultaneously like I did. Where did I go wrong?

Thanks again.

NP
closed account (S6k9GNh0)
The function expects a pointer, not an integer. Just casting an integer to a pointer doesn't fix this.
Understood.

NP
Topic archived. No new replies allowed.