linux - Why select do not tell me that a client wants to connect? -


i've made simple tcp server can test telnet program.

when running on windows, works expected, when running on linux, behavior strange:

  • telnet clients understand connected server,
  • the server not see clients (select return 0),
  • when kill server, clients detect disconnection.

i think missed in accept, listen or select.

what did missed?

thanks.

here's program source:

#include "headers.h" #define default_port 24891  /**  * test_server [ip port]  */ int main(int argc, char *argv[]) {     sockaddr_in sin;     socket_t sock;      /* listening socket creation */     sock = socket(af_inet, sock_stream, 0);     if (-1 == sock)         { die("socket()"); }              /* binding */     sin.sin_family = af_inet;     sin.sin_addr.s_addr = htonl(inaddr_any);     sin.sin_port = htons(default_port);     if (3 == argc)     {         sin.sin_addr.s_addr = inet_addr(argv[1]);         sin.sin_port = htons(strtol(argv[2], null, 0));     }      if (-1 == bind(sock, (sockaddr*) &sin, sizeof(sin)))         { die("bind()"); }      /* listening */     if (-1 == listen(sock, somaxconn))         { die("listen()"); }           while (1)     {         timeval timeout = { 1, 0 };         fd_set in_set;          fd_zero(&in_set);         fd_set(sock, &in_set);          // select set         int cnt = select(1, &in_set, null, null, &timeout);          if (cnt > 0)         {             // ask if event occurs on listening socket             if (fd_isset(sock, &in_set))             {                 /* new client wants connect */                 socket_t csock = accept(sock, null, null);                  send(csock, "hello\r\n", 7, 0);                 printf("new client!\n");                  close(csock);                             }         }              else if (cnt < 0)             { die("select"); }      }      /* closing listen socket */     close(sock);     printf("socket closed\n");      return 0; } 

you call select incorrectly. first parameter needs highest numbered fd fdset, plus one. see man page:

int select(int nfds, fd_set *readfds, fd_set *writefds,            fd_set *exceptfds, struct timeval *timeout); ....  nfds highest-numbered file descriptor in of 3 sets,  plus 1. 

the code may work, or may not, depends on fd returned "socket()".

in case value of "nfds" needs "sock + 1", need track highest numbered fd when doing select on multiple fd's.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -