Thomas Haupt
|
Re: Simple socket programming error
|
Thomas Haupt
06/30/2009 9:32 AM
post32824
|
Re: Simple socket programming error
Hi,
in fact, your small test application contained a number of problems.
Attached you'll find a working version; the diffs are discussed below:
19a20
> memset( &sin, 0, sizeof sin );
It's safer to zero out the sockaddr_in structue; otherwise, the bind() may fail.
============================================
43c44
< f = accept(f, (struct sockaddr *) &from, &len);
---
> g = accept(f, (struct sockaddr *) &from, &len);
You have to call accept() with the socket you did the listen() on, so using "f" as an argument is /correct/. But when
successful, accept() will return a new socket fd connected to the client (and not listened on) - so assigning the return
value to "f" is /wrong/; you will want to keep "f" all the time to be able to accept over and over.
============================================
45,47c46,48
< // g = accept(f, NULL, NULL);
< if (f < 0) {
< printf("f=%d\n", f);
---
>
> if (g < 0) {
> printf("g=%d\n", g);
Of course, with the accept() return value now ending up in "g", you'll need to do all the checking with that, as well...
============================================
53a55,56
> /* Handle the client request in separate process */
> break;
Now -- this, finally, is the really crucial one: after forking, your child process (propably dedicated to servicing the
accepted client connection) must /not/ end up trying to accept() again, as it did originally.
Your first server instance was just fine all the time; the accept() errors were all coming from the fork()ed server
child process...
Hope this helps,
- Thomas
|
|
|