Jump to ID:
Networking

Project Home

Discussions

Wiki

Project Info
Forum Topic - Simple socket programming error: (4 Items)
   
 
 
Simple socket programming error  
I am new to qnx. I have written a simple client/server code attached along. 

I get an error value EBADF(9), when i try to connect to the server socket.

Help me, to figure the reason for runtime error being returned.
Attachment: Text server.c 3.44 KB
Re: Simple socket programming error  
> I am new to qnx. I have written a simple client/server code attached along. 
> 
> I get an error value EBADF(9), when i try to connect to the server socket.
> 
> Help me, to figure the reason for runtime error being returned.

The error happened, when it failed to accept the client connection(ie, accept() call failed)
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
Attachment: Text tcp.good.c 3.49 KB
Re: Simple socket programming error  
Thanks Thomas for the detailed info.

Now the code works. One more change, i have to do in client() is remove the bind call.