int main (int argc, char *argv[]) { int sd = -1; int sndbuf = 0; int rcvbuf = 0; socklen_t optlen; if ((sd = socket (PF_INET, SOCK_STREAM, 0)) < 0) DieWithError("socket"); optlen = sizeof(sndbuf); if (getsockopt(sd, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen) < 0) DieWithError("getsockopt"); optlen = sizeof (rcvbuf); if (getsockopt(sd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &optlen) < 0) DieWithError("getsockopt"); printf("Socket Descriptor : %d\n", sd); printf(" Send buf: %d bytes\n", sndbuf); printf(" Recv buf: %d bytes\n", rcvbuf); close(sd); return 0; }
int main(int argc, char *argv[]) { int sock; struct sockaddr_in echoServAddr; unsigned short echoServPort; char *servIP; char *echoString; char echoBuffer[RCVBUFSIZE]; unsigned int echoStringLen; int bytesRcvd, totalBytesRcvd; if ((argc < 3) || (argc > 4)) { fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); } servIP = argv[1]; echoString = argv[2]; if (argc == 4) { echoServPort = atoi(argv[3]); } else { echoServPort = 7; } if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { DieWithError("socket() failed"); } memset(&echoServAddr, 0, sizeof(echoServAddr)); echoServAddr.sin_family = AF_INET; echoServAddr.sin_addr.s_addr = inet_addr(servIP); echoServAddr.sin_port = htons(echoServPort); if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) { DieWithError("connect() failed"); } echoStringLen = strlen(echoString); if (send(sock, echoString, echoStringLen, 0) != echoStringLen) { DieWithError("send() sent a different number of bytes than expected"); } totalBytesRcvd = 0; printf("Received: "); while (totalBytesRcvd < echoStringLen) { if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) { DieWithError("recv() failed or connection closed prematurely"); } totalBytesRcvd += bytesRcvd; echoBuffer[bytesRcvd] = '\0'; printf("%s\n", echoBuffer); } close(sock); exit(0); }
int CreateTCPServerSocket (unsigned short port) { int sock; /* socket to create */ struct sockaddr_in echoServAddr; /* Local address */ /* Create socket for incoming connections */ if ((sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { DieWithError ("socket() failed"); } info ("socket"); /* Construct local address structure */ memset( &echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(port); /* Local port */ /* Bind to the local address */ if (bind (sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) { DieWithError ("bind() failed"); } info_d ("bind", port); /* Mark the socket so it will listen for incoming connections */ if (listen (sock, MAXPENDING) < 0) { DieWithError ("listen() failed"); } info ("listen"); return (sock); }
void SIGIOHandler(int signalType) { struct sockaddr_in echoClntAddr; /* Address of datagram source */ unsigned int clntLen; /* Address length */ int recvMsgSize; /* Size of datagram */ char echoBuffer[ECHOMAX]; /* Datagram buffer */ do /* As long as there is input... */ { /* Set the size of the in-out parameter */ clntLen = sizeof(echoClntAddr); if ((recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) { /* Only acceptable error: recvfrom() would have blocked */ if (errno != EWOULDBLOCK) DieWithError("recvfrom() failed"); } else { printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); if (sendto(sock, echoBuffer, recvMsgSize, 0, (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr)) != recvMsgSize) DieWithError("sendto() failed"); } } while (recvMsgSize >= 0); /* Nothing left to receive */ }
void SIGIOHandler (int signalType) { struct sockaddr_in echoClntAddr; unsigned int clntLen; int recvMsgSize; char echoBuffer[ECHOMAX]; do { clntLen = sizeof (echoClntAddr); if ((recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *)&echoClntAddr, &clntLen)) < 0) { if (errno != EWOULDBLOCK) DieWithError("recvfrom() failed"); } else { printf("Handler client %s\n", inet_ntoa(echoClntAddr.sin_addr)); echoBuffer[recvMsgSize] = '\0'; printf("buf = %s\n", echoBuffer); if (sendto(sock, echoBuffer, recvMsgSize, 0, (struct sockaddr *)&echoClntAddr, sizeof(echoClntAddr)) != recvMsgSize) DieWithError("sendto() failed"); } } while (recvMsgSize >= 0); }
int CreateTCPServerSocket(unsigned short port) { int sock; struct sockaddr_in servAddr; // Create socket for incomming connection if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed!"); // Construct local addr structure memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure servAddr.sin_family = AF_INET; // Internet addr family servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incomming interface servAddr.sin_port = htons(port); // Local port // Bind to local addr if(bind(sock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0) DieWithError("bind() failed!"); // Mark the socket to listen for incomming connections if(listen(sock, MAXPENDING) < 0) DieWithError("listen() failed!"); return sock; }
int main(int argc, char *argv[]) { struct sockaddr_in echoServAddr; // Local address unsigned short echoServPort; // Server port WSADATA wsaData; // Structure for WinSock setup communication pthread_t pth; //Structure for threads echoServPort = 21; //Local port if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) // Load Winsock DLL { fprintf(stderr, "WSAStartup() failed"); exit(1); } if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) // Create socket for incoming connections DieWithError("socket() failed"); // Construct local address structure memset(&echoServAddr, 0, sizeof(echoServAddr)); // Zero out structure echoServAddr.sin_family = AF_INET; // Internet address family echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface echoServAddr.sin_port = htons(echoServPort); // Local port if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) // Bind to the local address < 0) DieWithError("bind() failed"); for (;;) { if (listen(servSock, MAXPENDING) < 0) DieWithError("listen() failed"); // Mark the socket so it will listen for incoming connections pthread_create(&pth, NULL, threadFunc, NULL); //if connection is found create a thread usleep(1); //lets see what our theads are doing } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ unsigned short echoServPort; /* Server port */ pthread_t threadID; /* Thread ID from pthread_create() */ struct ThreadArgs *threadArgs; /* Pointer to argument structure for thread */ if (argc != 2) /* Test for correct number of arguments */ { fprintf(stderr,"Usage: %s <SERVER PORT>\n", argv[0]); exit(1); } echoServPort = atoi(argv[1]); /* First arg: local port */ servSock = CreateTCPServerSocket(echoServPort); for (;;) /* run forever */ { clntSock = AcceptTCPConnection(servSock); /* Create separate memory for client argument */ if ((threadArgs = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs))) == NULL) DieWithError("malloc() failed"); threadArgs -> clntSock = clntSock; /* Create client thread */ if (pthread_create(&threadID, NULL, ThreadMain, (void *) threadArgs) != 0) DieWithError("pthread_create() failed"); printf("with thread %ld\n", (long int) threadID); } /* NOT REACHED */ }
void ClientEchoHandle(int clntSock, char *echoString){ int echoStringLen; // length of string to echo int bytesRcvd, totalBytesRcvd; // bytes read in single recv() and total bytes read //fgets(echoString, RCVBUFSIZE, stdin); // standard input to send msg echoStringLen = strlen(echoString); // determine input length // Send the string to the server if(send(clntSock, echoString, echoStringLen, 0) != echoStringLen){ DieWithError("send() sent a different number of bytes than expected"); } // Receive the same string back from the server totalBytesRcvd = 0; while(totalBytesRcvd < echoStringLen){ /* Receive up to the buffer size * (-1 to leave space for a null terminator) * bytes from the sender */ if((bytesRcvd = recv(clntSock, echoBuffer, RCVBUFSIZE-1, 0))<=0){ DieWithError("recv() failed or connection closed prematurely"); } totalBytesRcvd += bytesRcvd; // keep tally of total bytes echoBuffer[bytesRcvd]='\0'; // terminate the string! printf("%s\n",echoBuffer); } }
static void info_user (const char * prefix, const char * s) { struct tm ti; time_t t; if (tty_fptr == NULL) { tty_fptr = stdout; } if (argv_userprefix == true) { if (time (&t) == -1) { DieWithError ("time()"); } if (localtime_r (&t, &ti) == NULL) { DieWithError ("localtime()"); } fprintf (tty_fptr, "%02d:%02d:%02d %s:> ", ti.tm_hour, ti.tm_min, ti.tm_sec, prefix); } fprintf (tty_fptr, "%s", s); }
/* * Metodo que lee un archivo * @param buffer Contiene la información leída del archivo * @param file Nombre del archivo */ void read_file_process(char* buffer, char* file) { char* s; if((s = strrchr(file, '.')) == NULL) DieWithError("ERROR FATAL: El archivo no es del tipo texto"); else if(strcmp(s, ".txt") != 0) DieWithError("ERROR FATAL: El archivo no es del tipo texto"); FILE *fp = fopen(file, "r"); char c; int i; if(fp == NULL) DieWithError("ERROR FATAL: Ocurrio un error abriendo el archivo"); i = 0; while((c = getc(fp)) != EOF) { if (i > MES_SIZE-1) DieWithError("ERROR 500: El mensaje que se intenta cifrar es muy grande"); buffer[i++] = c; } if(i == 0) DieWithError("ERROR 501: El mensaje que se intenta cifrar está vacío"); else buffer[i] = '\0'; printf(buffer); fclose(fp); }
int openSocket() { int sock; /* Socket descriptor */ WSADATA wsaData; /* Structure for WinSock setup communication */ struct sockaddr_in echoServAddr; /* Echo server address */ if(WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) /* Load Winsock 2.0 DLL */ { fprintf(stderr, "WSAStartup() failed"); exit(1); } /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* Server IP address */ echoServAddr.sin_port = htons(MOTECOM_PORT_ADDR); /* Server port */ /* Create a reliable, stream socket using TCP */ if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); /* Establish the connection to the echo server */ if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); printf("socket %d\n", sock); return sock; }
int main(int argc, char *argv[]) { // connect to supplied address and send the greeting message to server int sock = Bootstrap(argv[1]); // process requests infinitely (we will be killed when done) int* nameLength; char status[3]; while(1) { int nameLength; if (scanf("%d", &nameLength) != 1) DieWithError("reading a filename length failed"); __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Length is %d", nameLength); char* filename; if ((filename = (char*) calloc(nameLength + 1, 1)) == NULL) DieWithError("calloc() failed"); __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Allocated %d - sized buffer", nameLength + 1); if (fgets(filename, nameLength + 1, stdin) == NULL) DieWithError("reading filename failed"); __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Attempting to open %s", filename); int mode; if (scanf("%d", &mode) != 1) DieWithError("reading a mode failed"); // freaking MIPS... if (mode&0x400) { mode ^= 0x400; mode |= O_APPEND; } if (mode&0x40) { mode ^= 0x40; mode |= O_CREAT; } __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Mode is %d", mode); int targetFd = open(filename, mode, S_IRWXU|S_IRWXG); if (targetFd > 0) { if (ancil_send_fds_with_buffer(sock, targetFd)) DieWithError("sending file descriptor failed"); } else { fprintf(stderr, "Error: failed to open a file - %s\n", strerror(errno)); } free(filename); close(targetFd); } return -1; }
int stringBufferLength(stringBuffer* L){ if (L==NULL) DieWithError("Function stringBufferLength: Non-NULL parameter expected.\n"); else return L->length; DieWithError("Function stringBufferLength: This line should never be executed.\n"); return -10; }
int main(int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ struct sockaddr_in echoServAddr; /* Local address */ struct sockaddr_in echoClntAddr; /* Client address */ unsigned short echoServPort; /* Server port */ unsigned char modbusAddr; /* 8-bit modbus addr */ unsigned int clntLen; /* Length of client address data structure */ if (argc != 3) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server Port> <Modbus Addr>\n", argv[0]); exit(1); } echoServPort = atoi(argv[1]); /* First arg: local port */ modbusAddr = (unsigned char) atoi(argv[2]); /* Second arg: modbus addr */ /* Create socket for incoming connections */ if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); /* Construct local address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ /* Bind to the local address */ if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("bind() failed"); /* Mark the socket so it will listen for incoming connections */ if (listen(servSock, MAXPENDING) < 0) DieWithError("listen() failed"); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ clntLen = sizeof(echoClntAddr); /* Wait for a client to connect */ if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) DieWithError("accept() failed"); /* clntSock is connected to a client! */ printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); HandleTCPClient(clntSock, modbusAddr); } /* NOT REACHED */ }
int main(int argc, char *argv[]) { int sock; /* Socket descriptor */ struct sockaddr_in echoServAddr; /* Echo server address */ unsigned short echoServPort; /* Echo server port */ char *servIP; /* IP address of server */ //char *echoString; /* String to send to echo server * char *echoCode; int echoStringLen = ECHOMAX; /* Length of string to echo */ if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */ { fprintf(stderr,"Usage: %s <Server IP> <Echo Code> [<Echo Port>]\n", argv[0]); exit(1); } servIP = argv[1]; /* First arg: server IP address (dotted quad) */ echoCode = argv[2]; /* Second arg: string to echo */ // if ((echoStringLen = strlen(*echoCode)) > ECHOMAX) /* Check input length */ // DieWithError("Echo word too long"); if (argc == 4) echoServPort = atoi(argv[3]); /* Use given port, if any */ else echoServPort = 8888; /* port 8888 defined on arduino */ /* Create a datagram/UDP socket */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet addr family */ echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */ echoServAddr.sin_port = htons(echoServPort); /* Server port */ /* Send the string to the server */ if (sendto(sock, echoCode, echoStringLen, 0, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) != echoStringLen) DieWithError("sendto() sent a different number of bytes than expected"); close(sock); exit(0); }
int main(int argc, const char *argv[]) { int serverSock; /* Socket descriptor for server */ int clientOneSock; /* Socket descriptor for client 1 */ unsigned int clientLength; struct sockaddr_in serverAddr; /* Local address */ struct sockaddr_in clientAddr1; user users[] = { {"Alice", "1234", 0, ""}, {"Bob", "123456", 0, ""} }; memset(&serverAddr, 0, sizeof(serverAddr)); /* Zero out structure */ serverAddr.sin_family = AF_INET; /* Internet address family */ serverAddr.sin_addr.s_addr = inet_addr(ADDRESS); /* Any incoming interface */ serverAddr.sin_port = htons(PORT); /* Local port */ if ((serverSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { DieWithError("Socket failed!"); } if (bind(serverSock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) { DieWithError("bind () failed"); } printf("Server Started!\n"); printf("Listening on %s:%d\n", ADDRESS, PORT); if (listen(serverSock, 2) < 0) { DieWithError("listen() failed"); } while (1) { clientLength = sizeof(&clientAddr1); if ((clientOneSock = accept(serverSock, (struct sockaddr *) &clientAddr1, &clientLength)) < 0) { DieWithError("accept() failed"); } printf("Client Connected: %s\n", inet_ntoa(clientAddr1.sin_addr)); while (1) { if (HandleTCPClient(clientOneSock, users) == 0) { printf("BROKE LOL\n"); close(clientOneSock); break; } } } return 0; }
void stringBufferInsert(stringBuffer* L, int address, char* s){ /*O(address + length(s)) time. O(1) when inserting after the last node. O(length(s)) space.*/ struct node_in_list_of_strings* newNode; /*Test if the parameters make sense*/ if (L == NULL || s == NULL) DieWithError("Function StringBufferInsert: Nonsensical parameter given: NULL string or NULL stringBuffer-pointer."); if (address > L->length || address < 0) DieWithError("Function StringBufferInsert: Nonsensical parameter given: Address < 0 or Address > (max address of stringBuffer + 1)\n"); /*Make a new node, and make for it a copy of the string that was passed to the function.*/ newNode = myalloc(sizeof(struct node_in_list_of_strings)); newNode->value = myalloc((strlen(s) + 1) * sizeof(char)); strcpy(newNode->value, s); /*Insert the new node into the list*/ if (address == 0){ /*Insert new node as first*/ if (L->length == 0){ newNode->next = NULL; L->first_node = L->last_node = newNode; } else { newNode->next = L->first_node; L->first_node = newNode; } } else if (address == L->length){ /*insert new node as last*/ newNode->next = NULL; L->last_node->next = newNode; L->last_node = newNode; } else { /*Insert it elsewhere. Go along the list until the address-1th node. Insert NewNode after this one. O(n)!*/ struct node_in_list_of_strings* p; int a; p = L->first_node; a = 0; while (a < (address - 1)){ a++; p = p->next; } /*p now points at the node before the address at which we have to insert. This is not the last node.*/ newNode->next = p->next; p->next = newNode; } L->length ++; return; }
int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in multicastAddr; /* Multicast address */ char *multicastIP; /* IP Multicast address */ unsigned short multicastPort; /* Server port */ char *sendString; /* String to multicast */ unsigned char multicastTTL; /* TTL of multicast packets */ unsigned int sendStringLen; /* Length of string to multicast */ if ((argc < 4) || (argc > 5)) /* Test for correct number of parameters */ { fprintf(stderr,"Usage: %s <Multicast Address> <Port> <Send String> [<TTL>]\n", argv[0]); exit(1); } multicastIP = argv[1]; /* First arg: multicast IP address */ multicastPort = atoi(argv[2]); /* Second arg: multicast port */ sendString = argv[3]; /* Third arg: String to multicast */ if (argc == 5) /* Is TTL specified on command-line? */ multicastTTL = atoi(argv[4]); /* Command-line specified TTL */ else multicastTTL = 1; /* Default TTL = 1 */ /* Create socket for sending/receiving datagrams */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Set TTL of multicast packet */ if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (void *) &multicastTTL, sizeof(multicastTTL)) < 0) DieWithError("setsockopt() failed"); /* Construct local address structure */ memset(&multicastAddr, 0, sizeof(multicastAddr)); /* Zero out structure */ multicastAddr.sin_family = AF_INET; /* Internet address family */ multicastAddr.sin_addr.s_addr = inet_addr(multicastIP);/* Multicast IP address */ multicastAddr.sin_port = htons(multicastPort); /* Multicast port */ sendStringLen = strlen(sendString); /* Find length of sendString */ for (;;) /* Run forever */ { /* Multicast sendString in datagram to clients every 3 seconds */ if (sendto(sock, sendString, sendStringLen, 0, (struct sockaddr *) &multicastAddr, sizeof(multicastAddr)) != sendStringLen) DieWithError("sendto() sent a different number of bytes than expected"); sleep(3); } /* NOT REACHED */ }
int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in multicastAddr; /* Multicast Address */ char *multicastIP; /* IP Multicast Address */ unsigned short multicastPort; /* Port */ char recvString[MAXRECVSTRING+1]; /* Buffer for received string */ int recvStringLen; /* Length of received string */ struct ip_mreq multicastRequest; /* Multicast address join structure */ if (argc != 3) /* Test for correct number of arguments */ { fprintf(stderr,"Usage: %s <Multicast IP> <Multicast Port>\n", argv[0]); exit(1); } multicastIP = argv[1]; /* First arg: Multicast IP address (dotted quad) */ multicastPort = atoi(argv[2]);/* Second arg: Multicast port */ /* Create a best-effort datagram socket using UDP */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Construct bind structure */ memset(&multicastAddr, 0, sizeof(multicastAddr)); /* Zero out structure */ multicastAddr.sin_family = AF_INET; /* Internet address family */ multicastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ multicastAddr.sin_port = htons(multicastPort); /* Multicast port */ /* Bind to the multicast port */ if (bind(sock, (struct sockaddr *) &multicastAddr, sizeof(multicastAddr)) < 0) DieWithError("bind() failed"); /* Specify the multicast group */ multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastIP); /* Accept multicast from any interface */ multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY); /* Join the multicast address */ if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *) &multicastRequest, sizeof(multicastRequest)) < 0) DieWithError("setsockopt() failed"); /* Receive a single datagram from the server */ if ((recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0) DieWithError("recvfrom() failed"); recvString[recvStringLen] = '\0'; printf("Received: %s\n", recvString); /* Print the received string */ close(sock); exit(0); }
int main(int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ unsigned short echoServPort; /* Server port */ pid_t processID; /* Process ID from fork() */ unsigned int childProcCount = 0; /* Number of child processes */ char *html_path = argv[2]; //assign html_path argument if (argc != 3) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]); exit(1); } echoServPort = atoi(argv[1]); /* First arg: local port */ servSock = CreateTCPServerSocket(echoServPort); for (;;) /* Run forever */ { clntSock = AcceptTCPConnection(servSock); /* Fork child process and report any errors */ if ((processID = fork()) < 0) DieWithError("fork() failed"); else if (processID == 0) /* If this is the child process */ { close(servSock); /* Child closes parent socket */ HandleTCPClient(clntSock, html_path); //send html_path as argument exit(0); /* Child process terminates */ } printf("with child process: %d\n", (int) processID); close(clntSock); /* Parent closes child socket descriptor */ childProcCount++; /* Increment number of outstanding child processes */ while (childProcCount) /* Clean up all zombies */ { processID = waitpid((pid_t) -1, NULL, WNOHANG); /* Non-blocking wait */ if (processID < 0) /* waitpid() error? */ DieWithError("waitpid() failed"); else if (processID == 0) /* No zombie to wait on */ break; else childProcCount--; /* Cleaned up after a child */ } } /* NOT REACHED */ }
int main(int argc, char *argv[]) { int sock; /* Socket descriptor */ struct sockaddr_in echoServAddr; /* Echo server address */ unsigned short echoServPort; /* Echo server port */ char *servIP; /* Server IP address (dotted quad) */ char *echoString; /* String to send to echo server */ char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ unsigned int echoStringLen; /* Length of string to echo */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); } servIP = argv[1]; /* First arg: server IP address (dotted quad) */ echoString = argv[2]; /* Second arg: string to echo */ if (argc == 4) echoServPort = atoi(argv[3]); /* Use given port, if any */ else echoServPort = 7; /* 7 is the well-known port for the echo service */ /* Create a reliable, stream socket using TCP */ if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */ echoServAddr.sin_port = htons(echoServPort); /* Server port */ /* Establish the connection to the echo server */ if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); while (1) { main2(sock); printf("sleep\n"); sleep(1); } close(sock); exit(0); }
int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in echoServAddr; /* Local address */ struct sockaddr_in echoClntAddr; /* Client address */ unsigned int cliAddrLen; /* Length of incoming message */ char echoBuffer[ECHOMAX]; /* Buffer for echo string */ unsigned short echoServPort; /* Server port */ int recvMsgSize; /* Size of received message */ if (argc != 2) { /* Test for correct number of parameters */ fprintf(stderr, "Usage: %s <UDP SERVER PORT>\n", argv[0]); exit(1); } echoServPort = atoi(argv[1]); /* First arg: local port */ /* Create socket for sending/receiving datagrams */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Construct local address structure */ memset(&echoServAddr, 0, sizeof (echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ /* Bind to the local address */ if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof (echoServAddr)) < 0) DieWithError("bind() failed"); /* Run forever */ for (;;) { /* Set the size of the in-out parameter */ cliAddrLen = sizeof (echoClntAddr); /* Block until receive message from a client */ if ((recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen)) < 0) DieWithError("recvfrom() failed"); printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); /* Send received datagram back to the client */ if (sendto(sock, echoBuffer, recvMsgSize, 0, (struct sockaddr *) &echoClntAddr, sizeof (echoClntAddr)) != recvMsgSize) DieWithError("sendto() sent a different number of bytes than expected"); } /* NOT REACHED */ }
/** Look for a client * This will handle commands but doesn't do anything ATM. * Think this will need to go in a thread */ void runClient(void) { // Network stuff from http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServer.c int serverSock; /* Socket descriptor for server */ int clientSock; /* Socket descriptor for client */ struct sockaddr_in echoServAddr; /* Local address */ struct sockaddr_in echoClntAddr; /* Client address */ unsigned short echoServPort; /* Server port */ unsigned int clntLen; /* Length of client address data structure */ echoServPort = 5570; /* This is the local port */ // System initialisations /* Construct local address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ /* Create socket for incoming connections */ if ((serverSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed\n"); /* Bind to the local address */ if (bind(serverSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("bind() failed"); /* Mark the socket so it will listen for incoming connections */ if (listen(serverSock, MAXPENDING) < 0) DieWithError("listen() failed"); /* Set the size of the in-out parameter */ clntLen = sizeof(echoClntAddr); /* Wait for a client to connect */ if ((clientSock = accept(serverSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) DieWithError("accept() failed"); /* clientSock is connected to a client! */ //printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); HandleTCPClient(clientSock); } // runClient
int main (int argc, char *argv[]) { int sock; /* Socket descriptor */ char * echoString; /* String to send to echo server */ char echoBuffer[RCVBUFSIZE]; /* Buffer for received string */ int echoStringLen; /* Length of string to echo */ int bytesRcvd; /* Bytes read in single recv() */ int bytesSend; /* Bytes read in single send() */ int i; /* counter for data-arguments */ parse_args (argc, argv); sock = CreateTCPClientSocket (argv_ip, argv_port); for (i = 0; i < argv_nrofdata; i++) { echoString = argv_data [i]; echoStringLen = strlen (echoString); /* Determine input length */ delaying (); // TODO: add code to send this string to the server; use send() bytesSend = send (sock, echoString, echoStringLen, 0); if (bytesSend < 0) { DieWithError ("send() failed"); } // TODO: add code to display the transmitted string in verbose mode; use info_s() info_s ("Sending to server: ", echoString); // TODO: add code to receive & display the converted string from the server // use recv() & printf() bytesRcvd = recv (sock, echoBuffer, RCVBUFSIZE-1, 0); if (bytesRcvd < 0) { DieWithError ("recv() failed"); } add_nt (echoBuffer, bytesRcvd); printf (" Received from server:'%s'\n", echoBuffer); } delaying (); close (sock); info ("close & exit"); exit (0); }
int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in broadcastAddr; /* Broadcast address */ char *broadcastIP; /* IP broadcast address */ unsigned short broadcastPort; /* Server port */ char *sendString; /* String to broadcast */ int broadcastPermission; /* Socket opt to set permission to broadcast */ unsigned int sendStringLen; /* Length of string to broadcast */ if (argc < 4) /* Test for correct number of parameters */ { fprintf(stderr,"Usage: %s <IP Address> <Port> <Send String>\n", argv[0]); exit(1); } broadcastIP = argv[1]; /* First arg: broadcast IP address */ broadcastPort = atoi(argv[2]); /* Second arg: broadcast port */ sendString = argv[3]; /* Third arg: string to broadcast */ /* Create socket for sending/receiving datagrams */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Set socket to allow broadcast */ broadcastPermission = 1; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission)) < 0) DieWithError("setsockopt() failed"); /* Construct local address structure */ memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */ broadcastAddr.sin_family = AF_INET; /* Internet address family */ broadcastAddr.sin_addr.s_addr = inet_addr(broadcastIP);/* Broadcast IP address */ broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */ sendStringLen = strlen(sendString); /* Find length of sendString */ for (;;) /* Run forever */ { /* Broadcast sendString in datagram to clients every 3 seconds*/ if (sendto(sock, sendString, sendStringLen, 0, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) != sendStringLen) DieWithError("sendto() sent a different number of bytes than expected"); sleep(3); /* Avoids flooding the network */ } /* NOT REACHED */ }
/* Make TCP Connection */ void new_connect ( struct sockaddr_in *s, int sock ) { struct sigaction act, oact; unsigned tcp_connect_timeout = DEFAULT_TCP_CONNECT_TIMEOUT; /* Set signal handler for alarm. just use sigaction() rather than signal() to prevent SA_RESTART */ act.sa_handler=sig_alarm; sigemptyset ( &act.sa_mask ); act.sa_flags=0; sigaction ( SIGALRM,&act,&oact ); /* Set alarm */ alarm ( tcp_connect_timeout ); /* Start connect */ if ( connect ( sock, ( struct sockaddr * ) &s, sizeof ( struct sockaddr_in ) ) != 0 ) { if ( errno == EINTR ) errno = ETIMEDOUT; DieWithError ( "connect() failed" ); } /* Cancel alarm */ alarm ( 0 ); }
int main (int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ int result; /* Result for thread creation */ pthread_t threadID; /* Thread ID from pthread_create() */ bool to_quit = false; parse_args (argc, argv); servSock = CreateTCPServerSocket (argv_port); while (to_quit == false) /* run until someone indicates to quit... */ { clntSock = AcceptTCPConnection (servSock); // Use the 'void *' parameter for passing clntSock result = pthread_create (&threadID, NULL, myThread, (void *) clntSock); if (result == 0) { info ("Succesfully created new thread"); } else { DieWithError ("pthread_create()"); } } // server stops... close (servSock); exit (0); }
/* * Procedimiento que escribe un archivo * @param buffer Mensaje a ser insertado en el archivo * @param file Nombre del archivo */ void write_file_process(char* buffer, char* file) { FILE *fp = fopen(file, "w"); if(fp == NULL) DieWithError("ERROR FATAL: Ocurrio un error abriendo el archivo"); fputs(buffer, fp); fclose(fp); }
int main(int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ struct sockaddr_in ClntAddr; /* Client address */ int ServPort; unsigned int clntLen; /* Length of client address data structure */ int size; long status=0L; char key[20]= {"keysm1"}; int create = TRUE; ServPort = (unsigned short)2005; servSock = CreateTCPServerSocket (ServPort); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ clntLen = sizeof(ClntAddr); /* Wait for a client to connect */ if ((clntSock = accept(servSock, (struct sockaddr *) &ClntAddr, &clntLen)) < 0) DieWithError("accept() failed"); /* clntSock is connected to a client! */ printf("Handling client %s\n", inet_ntoa(ClntAddr.sin_addr)); superHandleClient (clntSock); printf("AFTER Handling client %s\n", inet_ntoa(ClntAddr.sin_addr)); } /* NOT REACHED */ }