using select() to check for data availlability

Programming, for all ages and all languages.
Post Reply
Adek336

using select() to check for data availlability

Post by Adek336 »

Hi.

I'm still newbie to socket programming. One of my programs listens on a port, accepts one connection and then, in a loop it checks for data to read with select(). I connect to the socket with telnet, my program prints "accepted connection". When I write data through telnet, select() does not seem to see it.

Code: Select all

int main()
 {
int sfd1, sfd2;
struct sockaddr_in sin1,sin2;
int i;
int rozmiar=sizeof(sin2);
//create a socket
   sfd1= socket(AF_INET, SOCK_STREAM, 0);
//bind
   sin1.sin_family=AF_INET;
   sin1.sin_port=htons(4000);
   sin1.sin_addr.s_addr=INADDR_ANY;
   i= bind(sfd1, (struct sockaddr*)&sin1, sizeof(sin1));
   if (i<0) { printf("bind error\n"); exit(-1); }
//listen at the port
   listen(sfd1,1);
//accept one connection
   sfd2= accept(sfd1, (struct sockaddr*)&sin2, &rozmiar);
   if (sfd2<0) { printf("accept error?\n"); exit(-1); }

   printf("accepted\n");    //yup, this one is executed

   while (1) {
fd_set r;
   FD_ZERO(&r);
   FD_SET(sfd2, &r);
struct timeval u;
   u.tv_sec=0;
   u.tv_usec=100;
   i= select(1+1, &r,NULL,NULL, &u);

   if (i!=1) continue; //so: continue until "read from the file descriptor would not block"

//it doesn't get to this place ever...
   printf(".");fflush(stdout);
   }/*while*/
 }
The dots are never printed.
My connection throuth telnet looks like this:

Code: Select all

root@ttyp0[knoppix]# telnet localhost 4000
Trying 127.0.0.1...
Connected to Knoppix.
Escape character is '^]'.
f
g
f
g
Weirdly, the following code does respond for the data and puts them on screen.

Code: Select all

   while (1) {
char buf[20];
   i= recv(sfd2, buf, 19, 0);
   buf[i]='\0';
   printf("%s", buf);
   }/*while*/
Oh my this is ain't so easy as it looks ??? I think I should try the poll() call.

Well, now the question.. I would be very grateful if anybody would help me find the error.

Cheers,
Adrian
chris

Re:using select() to check for data availlability

Post by chris »

The first argument to select() is supposed to be the highest file descriptor number plus one, not the number of file descriptors plus one. Use sfd2 + 1 instead. BTW you don't really need select() in this example unless you just wanted to learn how to use it. A simple read() will work.
Adek336

Re:using select() to check for data availlability

Post by Adek336 »

Thnx now it works ;D

Indeed, what I'm trying to do is a program which will help me to play Age of Kings, behind a NAT. My program connects to the other computer(which must not be behind a NAT) and then sends all the tcp/ip and udp packets to it, where it sent back to the other player's comp.

Unfortunately there are still some tough bugs which prevent AoK from even recognising the other player ???
Thnx, Adrian
Post Reply