static int tcp_selectport(uint16_t portno) #endif { if (portno == 0) { /* No local port assigned. Loop until we find a valid listen port number * that is not being used by any other connection. NOTE the following loop * is assumed to terminate but could not if all 32000-4096+1 ports are * in used (unlikely). */ do { /* Guess that the next available port number will be the one after * the last port number assigned. */ portno = ++g_last_tcp_port; /* Make sure that the port number is within range */ if (g_last_tcp_port >= 32000) { g_last_tcp_port = 4096; } } #ifdef CONFIG_NETDEV_MULTINIC while (tcp_listener(domain, ipaddr, htons(g_last_tcp_port))); #else while (tcp_listener(htons(g_last_tcp_port))); #endif } else { /* A port number has been supplied. Verify that no other TCP/IP * connection is using this local port. */ #ifdef CONFIG_NETDEV_MULTINIC if (tcp_listener(domain, ipaddr, portno)) #else if (tcp_listener(portno)) #endif { /* It is in use... return EADDRINUSE */ return -EADDRINUSE; } } /* Return the selected or verified port number (host byte order) */ return portno; }
/* main program, just start listening and answering queries */ int main(int argc, char *argv[]) { int port = TSERVER_PORT; extern char *optarg; int opt; while ((opt=getopt(argc, argv, "p:")) != -1) { switch (opt) { case 'p': port = atoi(optarg); break; } } tcp_listener(port, run_webserver); return 0; }
int main(int argc, char **argv) { #ifdef WIN32 WSADATA wsa_data; WSAStartup(0x0201, &wsa_data); #endif try { SimpleEventLoop loop; //1. listen on PORT HelloWorldListener tcp_listener( &loop); tcp_listener.start_listen_on_tcp( CString("0.0.0.0:%d", PORT).c_str() ); //2. also we handle ctrl-C QuitSignalHandler control_c_handler(&loop); control_c_handler.start_handle_signal( SIGINT ); //3. also listen on a unix domain socket HelloWorldListener un_listener( &loop); un_listener.start_listen_on_un( ".haha" ); //4. the main loop loop.run(); printf("done\n"); } catch (std::exception& ex) { LOG_ERROR("Exception in main(): %s\n", ex.what()); return 1; } catch (...) { LOG_ERROR("Unknown exception in main()\n"); return 1; } return 0; }