int find_free_port(int start, int end) { int port; if (start <= 0) { start = 1024; } if (end <= 0 || end > 65530) { end = 65530; } for (port = start; port <= end; port++) { int sock = listen_tcp(port, htonl(INADDR_ANY), 0); if (sock >= 0) { close(sock); sock = listen_tcp(port, htonl(INADDR_LOOPBACK), 0); if (sock >= 0) { close(sock); return port; } } } return 0; }
void listen_call_handler(unsigned long long uniqueSockID, int threads, unsigned char *buf, ssize_t len) { int index; int backlog; u_char *pt; PRINT_DEBUG(""); pt = buf; backlog = *(int *) pt; pt += sizeof(int); if (pt - buf != len) { PRINT_DEBUG("READING ERROR! CRASH, diff=%d len=%d", pt - buf, len); nack_send(uniqueSockID, listen_call); return; } PRINT_DEBUG(""); index = findjinniSocket(uniqueSockID); PRINT_DEBUG(""); if (index == -1) { PRINT_DEBUG( "CRASH !!! socket descriptor not found into jinni sockets SO pipe descriptor to reply is not found too "); nack_send(uniqueSockID, listen_call); return; } PRINT_DEBUG(""); if (jinniSockets[index].type == SOCK_DGRAM) listen_udp(uniqueSockID, backlog); else if (jinniSockets[index].type == SOCK_STREAM) listen_tcp(uniqueSockID, backlog); else if (jinniSockets[index].type == SOCK_RAW) { listen_icmp(uniqueSockID, backlog); } else { PRINT_DEBUG("unknown socket type has been read !!!"); nack_send(uniqueSockID, listen_call); } }
// main function int _tmain(int argc, _TCHAR* argv[]) { int code = 0; int interactive = 0; int tcp_port = 13110; int com_port = 0; // set console to display special characters correctly setlocale(LC_ALL, ""); printf("WinOPDI test program. Arguments: [-i] [-tcp <port>] [-com <port>]\n"); printf("-i starts the interactive master.\n"); for (int i = 1; i < argc; i++) { if (_tcscmp(argv[i], _T("-i")) == 0) { interactive = 1; } else if (i < argc - 1) { if (_tcscmp(argv[i], _T("-tcp")) == 0) { // parse tcp port number tcp_port = _wtoi(argv[++i]); if ((tcp_port < 1) || (tcp_port > 65535)) { printf("Invalid TCP port number: %d\n", tcp_port); exit(1); } } else if (_tcscmp(argv[i], _T("-com")) == 0) { // parse com port number com_port = _wtoi(argv[++i]); if ((com_port < 1) || (com_port > 32)) { printf("Invalid COM port number: %d\n", com_port); exit(1); } } else { printf("Unrecognized argument: %s\n", argv[i]); exit(1); } } else { printf("Invalid syntax: missing argument\n"); exit(1); } } // master? if (interactive) { code = start_master(); } else { opdi_set_timeout(65535); // slave if (com_port > 0) { LPCTSTR comPort = (LPCTSTR)malloc(6); wsprintf((LPTSTR)comPort, _T("COM%d"), com_port); code = listen_com(comPort, 115000, ONESTOPBIT, NOPARITY, 8, 1000); } else { code = listen_tcp(tcp_port); } } printf("Exit code: %d", code); exit(code); }