int main(int argc, char** argv) { int serverSocket; //Socket descriptor for server int clientSocket; //Socket descriptor for client struct sockaddr_in echoServerAddr; //local address struct sockaddr_in echoClientAddr; //client address unsigned short echoServerPort; //server port unsigned int clientLen; //length of client address data structure // if(argc != 2){ // fprintf(stderr, "Usage %s <Server Port>\n", argv[0]); // exit(1); // } echoServerPort = PORT; //create socket for incoming connections if((serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ dieWithError("socket() failed"); } //construct local address structure memset(&echoServerAddr, 0, sizeof(echoServerAddr)); //zero out structure echoServerAddr.sin_family = AF_INET; //internet address family echoServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); //any incoming interface echoServerAddr.sin_port = htons(echoServerPort); //local port //bind to the local address if(bind(serverSocket, (struct sockaddr*)&echoServerAddr, sizeof(echoServerAddr)) < 0){ dieWithError("bind() failed"); } //mark the socket so it will listen for incoming connections if(listen(serverSocket, MAXPENDING) < 0){ dieWithError("listen() failed"); } //set the size of the in-out parameter clientLen = sizeof(echoClientAddr); //wait for client to connect if((clientSocket = accept(serverSocket, (struct sockaddr*)&echoClientAddr, &clientLen)) < 0){ dieWithError("accept() failed"); } //clientSocket is connected to a client printf("Handling client %s\n", inet_ntoa(echoClientAddr.sin_addr)); handleTCPClient(clientSocket); }
int main(int argc, char** argv) { char dle_etx[] = "\x10\03"; int sock; //socket descrriptor struct sockaddr_in echoServerAddr; //echo server address unsigned short echoServerPort; //echo server port char* serverIP; //server ip address (dotted quad) char echoBuffer[RCVBUFSIZE]; //buffer for echo string unsigned int echoStringLen; //length of string to echo int bytesRecieved, totalBytesRecieved; //bytes read in single recv and total bytes read int messagesSent, messages; if(argc < 3 || argc > 7){ //test for correct arguments fprintf(stderr, "Usage: %s <Server IP> <string 1> [string 2] [string 3] [string 4] [string 5]\n", argv[0]); exit(1); } messages = argc - 2; serverIP = argv[1]; echoServerPort = PORT; //create a reliable stream socket using TCP if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ dieWithError("socket() failed"); } //construct server address structure memset(&echoServerAddr, 0, sizeof(echoServerAddr)); //zero out structure echoServerAddr.sin_family = AF_INET; //internet address family echoServerAddr.sin_addr.s_addr = resolveName(serverIP); //server ip address echoServerAddr.sin_port = htons(echoServerPort); //server port //establish connection to the echo server if(connect(sock, (struct sockaddr*)&echoServerAddr, sizeof(echoServerAddr)) < 0){ dieWithError("connect() failed"); } //TODO: echo all messages and dle etx messagesSent = 0; do { //printf("sending %s\n",argv[2+messagesSent] ); sendMessage(sock, argv[2+messagesSent]); messagesSent++; } while(messagesSent < messages); sendMessage(sock, dle_etx); close(sock); //close socket exit(0); }
void handleTCPClient(int clientSocket) { char echoBuffer[RECVBUFSIZE]; int msgSize; char dle_etx[] = "\x10\x03"; int sent; //recieve message from client int count = 0; while(1) { //see if there is more data to recieve if((msgSize = recv(clientSocket, echoBuffer, RECVBUFSIZE, 0)) < 0){ dieWithError("recv() failed"); } echoBuffer[msgSize] = '\0'; //printf("recved %s\n", echoBuffer); if((sent = send(clientSocket, echoBuffer, msgSize, 0) )!= msgSize){ printf("ms = %d, but sent %d\n",msgSize, sent ); dieWithError("send() failed"); } if(msgSize == 0){ break; } if(strcmp(dle_etx, echoBuffer) == 0){ break; } count++; } printf("EnhancedServer echoed %d strings.\n",count); //recieve last packet to finish recv(clientSocket, echoBuffer, RECVBUFSIZE, 0); close(clientSocket); // } }
// send a message to the client void sendStruct(){ //get the size in bytes of the struct to be sent for error checking sendMessageSize = sizeof(msgToClient); printf("%s\n%d\n%u",msgToClient.flightID, msgToClient.numberOfSeats,msgToClient.stat); /* Send datagram back to the client */ if (sendto(sock,(struct serverRequest *) &msgToClient, sendMessageSize, 0, (struct sockaddr *) &clntAddr, sizeof(clntAddr)) != sendMessageSize) dieWithError("sendto() sent a different number of bytes than expected"); }
unsigned long resolveName(char* name) { struct hostent *host; if((host = gethostbyname(name)) == NULL){ dieWithError("gethostbyname() failed"); } return *((unsigned long *) host->h_addr_list[0]); }
job_eval_result_t processJob(int workloadType) { job_eval_result_t result; job_result_t jobProduct; if (!isProperWorkloadType(workloadType)) { dieWithError("Invalid workload type\n"); } double sleepTime = generateRandomSleepTime(workloadType); preciseSleep(sleepTime); jobProduct = generateRandomIntegerArray(workloadType); result.job_result = jobProduct; result.sleepTime = sleepTime; return result; }
void sendMessage(int sock, char* message) { int mlen = strlen(message); if(mlen > 12){ printf("The string \"%s\" is longer than 12 bytes\n", message); return; } int totalBytesRecieved, bytesRecieved; char buffer[RCVBUFSIZE]; if(send(sock, message, mlen, 0) != mlen){ dieWithError("send() sent a different number of bytes than expected"); } totalBytesRecieved = 0; // printf("Recieved: "); //set to print the echoed string while(totalBytesRecieved < mlen){ //recieve up to the buffer size (minus 1 to leave space for the null terminator) bytes from the sender if((bytesRecieved = recv(sock, buffer, RCVBUFSIZE-1, 0)) <= 0){ dieWithError("recv() failed for connection closed prematurely"); } totalBytesRecieved += bytesRecieved; //keep tally of total bytes buffer[bytesRecieved] = '\0'; //terminate string if(strcmp(DLE_ETX, buffer) == 0){ printf("EnhancedClient done"); } else { printf("EnhancedClient recieved: %s\n", buffer); } } //printf("\n"); }
int main(int argc, char *argv[]){ if (argc != 2) /* Test for correct number of parameters */ { fprintf(stderr,"Usage: %s <UDP SERVER PORT>\n", argv[0]); return 1; } // assigan the port number servPort = atoi(argv[1]); /* Create socket for sending/receiving datagrams */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) dieWithError("socket() failed"); /* Construct local address structure */ memset(&servAddr, 0, sizeof(servAddr)); /* Zero out structure */ servAddr.sin_family = AF_INET; /* Internet address family */ servAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ servAddr.sin_port = htons(servPort); /* Local port */ /* Bind to the local address */ if (bind(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) dieWithError("bind() failed"); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ cliAddrLen = sizeof(clntAddr); //receive(); handleMsg(); } return 0; }
int main(int argc, char** argv) { if(argc != 2) dieWithError("No commandline parameter given.\nEnter parameter 0 for a static image with depth of field.\nEnter parameter 1 for a look-around mode with mouse movements."); lookAround = atoi(argv[1]); initOpenGL(argc, argv); intDragons(); glutDisplayFunc(go); if(lookAround) { printUsage(); glutIdleFunc(idle); glutKeyboardFunc(handleKeys); glutMouseFunc(handleMouse); glutMotionFunc(handleMovedMouse); } else glutKeyboardFunc(getOut); glutMainLoop(); return 0; }
int main(int argc, char *argv[]) { //variables: char *robotHost, *robotID; int imageID; //UDP variables: int udpSock; struct sockaddr_in udpServAddr; /* Local address */ struct sockaddr_in udpClntAddr; /* Client address */ unsigned int cliAddrLen; /* Length of incoming message */ char udpBuffer[MAX]; /* Buffer for echo string */ unsigned short udpPort; int recvMsgSize; /* Size of received message */ // parse for port number for UDP connection with client if (argc != 5) /* Test for correct number of arguments */ { dieWithError("Usage: robotServer <UDP Server Port> <Robot Hostname> <Robot ID> <Image ID>\n"); } udpPort = atoi(argv[1]); robotHost = argv[2]; robotID = argv[3]; imageID = atoi(argv[4]); /* Create socket for sending/receiving datagrams */ if ((udpSock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) dieWithError("socket() failed"); /* Construct local address structure */ memset(&udpServAddr, 0, sizeof(udpServAddr)); /* Zero out structure */ udpServAddr.sin_family = AF_INET; /* Internet address family */ udpServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ udpServAddr.sin_port = htons(udpPort); /* Local port */ /* Bind to the local address */ printf("UDPEchoServer: About to bind to port %d\n", udpPort); if (bind(udpSock, (struct sockaddr *) &udpServAddr, sizeof(udpServAddr)) < 0) dieWithError("bind() failed"); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ cliAddrLen = sizeof(udpClntAddr); /* Block until receive message from a client */ if ((recvMsgSize = recvfrom(udpSock, udpBuffer, MAX, 0, (struct sockaddr *) &udpClntAddr, &cliAddrLen)) < 0) dieWithError("recvfrom() failed"); printf("Handling client %s\n", inet_ntoa(udpClntAddr.sin_addr)); //variables again char robotID2[100], requestString[100]; char* result = NULL; int resultSize = -1; char buffer2[512]; buffer2[0] = 0; uint32_t requestID; memcpy(&requestID,udpBuffer,4); strcpy(robotID2,udpBuffer+4); if(strcmp(robotID2, robotID) != 0) dieWithError("robot ID's do not match"); int padding = 4+strlen(robotID2)+1; strcpy(requestString, udpBuffer+padding); printf("requestString: %s\n", requestString); if (strncmp(requestString, "GET IMAGE", 9) == 0) { sprintf(buffer2, "/snapshot?topic=/robot_%d/image?width=600?height=500", imageID); result = castaraConnect(robotHost, 8081, buffer2, &resultSize); } else if (strncmp(requestString, "MOVE", 4) == 0) { double velocity; sscanf(requestString+4, "%lf", &velocity); sprintf(buffer2, "/twist?id=%s&lx=%lf", robotID2, velocity); result = castaraConnect(robotHost, 8082, buffer2, &resultSize); } else if (strncmp(requestString, "TURN", 4) == 0) { double velocity; sscanf(requestString+4, "%lf", &velocity); sprintf(buffer2, "/twist?id=%s&az=%lf", robotID2, velocity); result = castaraConnect(robotHost, 8082, buffer2, &resultSize); } else if (strncmp(requestString, "GET LASERS", 10) == 0) { sprintf(buffer2, "/state?id=%s", robotID2); result = castaraConnect(robotHost, 8083, buffer2, &resultSize); } else if (strncmp(requestString, "GET GPS", 7) == 0) { sprintf(buffer2, "/state?id=%s", robotID2); result = castaraConnect(robotHost, 8082, buffer2, &resultSize); } else if (strncmp(requestString, "GET DGPS", 8) == 0) { sprintf(buffer2, "/state?id=%s", robotID2); result = castaraConnect(robotHost, 8084, buffer2, &resultSize); } else if (strncmp(requestString, "STOP", 4) == 0) { sprintf(buffer2, "/twist?id=%s&lx=0", robotID2); result = castaraConnect(robotHost, 8082, buffer2, &resultSize); } else { printf("bad request"); *result = '\0'; } printf("sending %s out", buffer2); char responseBuffer[1000]; memcpy(responseBuffer, (char*)&requestID, 4); uint32_t messageCount = (resultSize/988)+1; messageCount = htonl(messageCount); memcpy(responseBuffer+4, (char*)&messageCount, 4); int responseOffset = 0; int responseLeft = resultSize; int responseSize; int i; for(i=0;i<(int)ntohl(messageCount);i++){ uint32_t sequenceNum = i; sequenceNum = htonl(sequenceNum); memcpy(responseBuffer+8, (char*)&sequenceNum, 4); if(responseLeft >= 988){ responseSize = 988; }else{ responseSize = responseLeft; } memcpy(responseBuffer+12, result+responseOffset, responseSize); /* Send received datagram back to the client */ if (sendto(udpSock, responseBuffer, responseSize+12, 0, (struct sockaddr *) &udpClntAddr, sizeof(udpClntAddr)) < 0){ printf("sendto() sent a different number of bytes than expected\n"); exit(1); } responseLeft -= responseSize; responseOffset += responseSize; } } return 0; }
bool authenticate(int commSocket, char *user, char *pass) { /**Receive challenge**/ int totalBytes = 0; char challenge_buffer[CHALLENGE_SIZE + 1]; int BYTES_TO_RECEIVE = CHALLENGE_SIZE; debugPrintf("Begin receiving challenge\n"); while(totalBytes < BYTES_TO_RECEIVE) { int received; if((received = recv(commSocket, &challenge_buffer[totalBytes], CHALLENGE_SIZE - totalBytes, 0)) <= 0) dieWithError("recv(...) failed."); totalBytes += received; debugPrintf("Received %d bytes\n", received); } challenge_buffer[CHALLENGE_SIZE] = '\0'; debugPrintf("Challenge received: %s\n", challenge_buffer); /**force username to all lower*/ for(int i = 0; i < strlen(user); i++) { user[i] = tolower(user[i]); } /**Hash user + pass + challenge**/ int preHashSize = strlen(user) + strlen(pass) + CHALLENGE_SIZE + 1; char preHash[preHashSize]; memcpy(preHash, user, strlen(user)); memcpy(&preHash[strlen(user)], pass, strlen(pass)); memcpy(&preHash[strlen(user) + strlen(pass)], challenge_buffer, CHALLENGE_SIZE); preHash[preHashSize - 1] = '\0'; debugPrintf("Pre-hashed string: %s\n", preHash); unsigned int result = *md5(preHash, strlen(preHash)); debugPrintf("Hashed result: %#x\n", result); /** Send length of username to server, so it knows how long to recv when reading username. Then send the username itself. Then send hashed result (fixed length) to server **/ int usernameLength = strlen(user); send(commSocket, &usernameLength, sizeof(int), 0); send(commSocket, user, usernameLength, 0); send(commSocket, &result, sizeof(result), 0); debugPrintf("Hash sent\nAwaiting authentication\n"); /**Receive auth response**/ totalBytes = 0; char authResponseBuffer[sizeof(int)]; int authResponse; BYTES_TO_RECEIVE = sizeof(int); while(totalBytes < BYTES_TO_RECEIVE) { int received; if((received = recv(commSocket, &authResponseBuffer[totalBytes], BYTES_TO_RECEIVE - totalBytes, 0)) <= 0) dieWithError("recv(...) failed."); totalBytes += received; debugPrintf("Received %d bytes\n", received); } authResponse = (*(int*)authResponseBuffer); debugPrintf("AuthResponse: %d\n", authResponse); if(authResponse == AUTH_SUCCESS) { return true; } else { return false; } }
/** * TCP banking client. Allows user to deposit, withdraw * and check balance. Must interact with a server-tcp program. * Skeleton code taken from TCP/IP Sockets in C by Donahoo * and Calvert. * */ int main(int argc, char *argv[]) { /**Ensure proper command line args**/ if (argc != 6 && argc != 7) { dieWithError("Usage: remotebank-tcp <Server IP>:<Port> <Username> <Password> <Transaction Type> <Transaction Amount> [-d]"); } if (argc == 7) { if(strcmp(argv[6], "-d") == 0) { debugMode = true; } else { dieWithError("\nUsage: remotebank-tcp <Server IP>:<Port> <Username> <Password> <Transaction Type> <Transaction Amount> [-d]\n"); } } char *name = argv[2]; char *pass = argv[3]; if(strlen(name) > 30 || strlen(pass) > 30) { dieWithError("\nUsername/password must be max 30 characters.\n"); } //ensure valid request type if(strcasecmp(argv[4], "deposit") && strcasecmp(argv[4], "withdraw") && strcasecmp(argv[4], "checkbal")) { dieWithError("\nTransaction type must be one of the following:\n\tdeposit\n\twithdraw\n\tcheckbal\n"); } /**Get position of colon within first argument**/ char *colon = strchr(argv[1], ':'); int colonPosition = colon - argv[1]; if(colonPosition > 15) { dieWithError("\nInvalid IP address. Please use dotted quad notation.\n"); } /**Substring first argument into IP and Port**/ /**IP**/ char serverIp[colonPosition + 1]; //+1 for \0 character memcpy(serverIp, &argv[1][0], colonPosition); serverIp[colonPosition] = '\0'; if(((int)inet_addr(serverIp)) < 0) dieWithError("\nInvalid IP address. Please use dotted quad notation.\n"); /**PORT**/ int portStrLength = strlen(argv[1]) - colonPosition; char argumentPortStr[portStrLength + 1]; memcpy(argumentPortStr, &argv[1][colonPosition + 1], portStrLength); argumentPortStr[portStrLength - 1] = '\0'; int serverPortAsInt = atoi(argumentPortStr); //parses to int if(serverPortAsInt > USHRT_MAX) { dieWithError("\nInvalid port number.\n"); } unsigned short serverPort = (unsigned short)serverPortAsInt; debugPrintf("IP: %s, Port: %d\n", serverIp, serverPort); /**Create socket**/ int commSocket; if((commSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { dieWithError("socket(...) failed"); } debugPrintf("TCP socket created. File descriptor: %d\n", commSocket); /**Fill out address structure for server address**/ socket_address serverAddress; memset(&serverAddress, 0, sizeof(serverAddress)); //zero out serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = inet_addr(serverIp); serverAddress.sin_port = htons(serverPort); debugPrintf("Connecting to %s:%d . . .\n", serverIp, serverPort); //establish connection if(connect(commSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { dieWithError("connect(...) failed."); } debugPrintf("Connection successful\n"); socket_address clientAddress; int address_size = sizeof(clientAddress); getsockname(commSocket, (struct sockaddr *)&clientAddress, &address_size); debugPrintf("Client is on %s:%d\n", inet_ntoa(clientAddress.sin_addr), clientAddress.sin_port); /** AUTHENTICATE! **/ if(!authenticate(commSocket, argv[2], argv[3])) { printf("Authentication failed\n"); close(commSocket); exit(0); } debugPrintf("Authentication successful\n"); /** Fill out transaction request struct **/ int requestType; double requestAmount; if(strcasecmp(argv[4], "deposit") == 0) { requestType = TRANSACTION_DEPOSIT; } else if(strcasecmp(argv[4], "withdraw") == 0) { requestType = TRANSACTION_WITHDRAW; } else if(strcasecmp(argv[4], "checkbal") == 0) { requestType = TRANSACTION_CHECKBAL; } else { dieWithError("Internal error processing request type."); } requestAmount = atof(argv[5]); /**Send transaction request**/ send(commSocket, &requestType, sizeof(requestType), 0); send(commSocket, &requestAmount, sizeof(requestAmount), 0); debugPrintf("Sent request. Type: %d -- Amount: %.2f\n", requestType, requestAmount); /**Receive transaction response**/ int totalBytes = 0; int BYTES_TO_RECEIVE = sizeof(int) + sizeof(double); int response; double updatedBalance; char responseBuffer[BYTES_TO_RECEIVE]; debugPrintf("Receiving transaction response . . .\n"); while(totalBytes < BYTES_TO_RECEIVE) { int received; if((received = recv(commSocket, &responseBuffer[totalBytes], BYTES_TO_RECEIVE - totalBytes, 0)) < 0) dieWithError("Failed receiving transaction response"); totalBytes += received; debugPrintf("Received %d bytes\n", received); } response = (*(int*)responseBuffer); updatedBalance = (*(double*)&responseBuffer[sizeof(int)]); /**PRINT RESULTS**/ debugPrintf("Response: %d -- Balance: $%.2f\n", response, updatedBalance); printf("\nWelcome to online banking, %s\n", argv[2]); if(requestType == TRANSACTION_DEPOSIT) { if(response == RESPONSE_SUCCESS) { printf("Deposit of $%.2f successful. New balance: %.2f\n", requestAmount, updatedBalance); } else if(response == RESPONSE_INVALID_REQUEST) { printf("Invalid deposit request\n"); } } else if(requestType == TRANSACTION_WITHDRAW) { if(response == RESPONSE_SUCCESS) { printf("Withdrawal of $%.2f successful. New balance: %.2f\n", requestAmount, updatedBalance); } else if(response == RESPONSE_INSUFFICIENT_FUNDS) { printf("Insufficient funds to withdraw $%.2f. Balance remains at $%.2f\n", requestAmount, updatedBalance); } else { printf("Invalid withdraw request\n"); } } else if(requestType == TRANSACTION_CHECKBAL) { if(response == RESPONSE_SUCCESS) { printf("Your balance is %.2f\n", updatedBalance); } else if(response == RESPONSE_INVALID_REQUEST) { printf("Invalid checkbal request\n"); } } close(commSocket); exit(0); }
int main(int argc, char *argv[]) { int sock; /* Socket descriptor */ struct sockaddr_in servAddr;/* Server address */ unsigned short servPort; /* Server port */ char *servIP; /* Server IP address (dotted quad) */ char fileName[1024]; /* File Path */ char sendBuffer[BUFSIZE]; /* Buffer for string */ if ((argc < 4) || (argc > 4))/* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server IP> <Server Port> <File Path>\n", argv[0]); exit(1); } servIP = argv[1]; /* First arg: server IP address (dotted quad) */ servPort = atoi(argv[2]); /* Second arg: server port */ strcpy(fileName,argv[3]); /* Third arg: file path perserved as an array */ /* Open file to be sent */ FILE *fp = fopen(fileName,"rb"); size_t fileSize = sizeof(*fp); printf("size of file in bytes:%ld",fileSize); if (fp == NULL) { fprintf(stderr,"could not open file\n"); return -1; } /* 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(&servAddr, 0, sizeof(servAddr)); /* Zero out structure */ servAddr.sin_family = AF_INET; /* Internet address family */ servAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */ servAddr.sin_port = htons(servPort); /* Server port */ /* Establish the connection to the server */ if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) dieWithError("connect() failed"); int count = 0; while (!feof(fp)) { memset(sendBuffer, 0 ,BUFSIZE); size_t bytesRead = fread(sendBuffer,1,BUFSIZE,fp); printf("%ld\n",bytesRead); ++count; /* Send the string to the server */ if (send(sock, sendBuffer, BUFSIZE, 0) < 0) dieWithError("send(): ERROR writing to socket"); } printf("sent packet count: %d\n", count); fclose(fp); close(sock); exit(0); }
int main(int argc, char** argv) { //all my variables int theSocket; //the socket unsigned short serverPort; //the server port int numUsers = 0; //current number of users int userLimit = 10; //the user limit, will adjust when needed int userIndex; //used when addressing users in the data structure char cmd[100]; //whatever the user types in after the server starts //structures Message incoming; //incoming message Message outgoing; //outgoing message Client *users; //all the users pid_t processID; //the child process ID bool *handlingTalk; //bool if talking is being handled memset(&handlingTalk, 0, sizeof (bool)); handlingTalk = mmap(NULL, sizeof (bool), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); //needs to be shared among all of the threads //address variables struct sockaddr_in theServerAddress; //the local address struct sockaddr_in theClientAddress; //the client address unsigned int clientAddressLength = sizeof (theClientAddress); //length of the client address //handle command line stuff //create socket if ((theSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { dieWithError("socket() failed"); } serverPort = DEFAULT_PORT; //create the address structure memset(&theServerAddress, 0, sizeof (theServerAddress)); // Zero out structure theServerAddress.sin_family = AF_INET; // Internet address family theServerAddress.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface theServerAddress.sin_port = htons(serverPort); // Local port //bind() to the address if (bind(theSocket, (struct sockaddr *) &theServerAddress, sizeof (theServerAddress)) < 0) { dieWithError("bind() failed"); } puts("# Engaged."); fflush(stdout); processID = fork(); //two threads, if (processID > 0) { //parent: server commands for (;;) { char cmd[99]; //whatever the user types in after the server starts for (;;) { fgets(cmd, 100, stdin); cmd[strlen(cmd) - 1] = '\0'; if (strcmp(cmd, "exit") == 0 || strcmp(cmd, "logout") == 0) { //exit/logout: safely closes down the server puts("# Connection Closed."); kill(0, SIGTERM); //exits the program } else if (strcmp(cmd, "help") == 0 || strcmp(cmd, "?") == 0) { puts("# It's working. 'exit' and 'logout' are used to quit."); } else if (strcmp(cmd, "who") == 0 || strcmp(cmd, "list") == 0) { //who: displays on the server the current users logged in } else if (strcmp(cmd, "say") == 0 || strcmp(cmd, "talk") == 0) { //say: says a global message from the server } else if (strcmp(cmd, "\0") != 0) { puts("# Invalid Command."); } } } } else if (processID == 0) { //child: sever operation, mainly just retrieving and responding to messages users = calloc(userLimit, sizeof (Client)); //memmory for data structure int i; //for loops (which are primarily for-loops) int j; //for counting (which is primarily done with numbers) memset(&incoming, 0, sizeof (incoming)); //memory memset(&outgoing, 0, sizeof (outgoing)); //memory outgoing.senderID = SERVER_ID; for (;;) { recvfrom(theSocket, &incoming, sizeof (incoming), MSG_PEEK, (struct sockaddr *) &theClientAddress, &clientAddressLength); switch (incoming.type) { case TAG_LOGIN: fflush(stdout); recvfrom(theSocket, &incoming, sizeof (incoming), 0, (struct sockaddr *) &theClientAddress, &clientAddressLength); printf("\n# Received login request from %04i...\n", incoming.senderID); //LOGIN, adds the user to the list of logged in users, sends a message to each other user that the user logged in outgoing.type = TAG_LOGIN; //the outgoing message type is login outgoing.senderID = incoming.senderID; userIndex = getUserIndex(incoming.senderID, numUsers, users); if (userIndex >= 0 && users[userIndex].isLoggedIn == true) { //the user has already logged in outgoing.confirm = false; if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...user %04i is already logged in.\n", incoming.senderID); break; } outgoing.confirm = true; //the user has logged in //send login confirmation if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...login confirmation send to %04i...\n", incoming.senderID); sprintf(outgoing.data, "%d", incoming.senderID); //inserts the user id into a string to send to all the other users outgoing.senderID = SERVER_ID; printf("# ...%04i logged in.\n", incoming.senderID); printf("# Sending login notifications...\n"); //sends message to all users that the new user logged in for (i = 0; i < numUsers; i++) { if (users[i].isLoggedIn == true) { if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &users[i].theUDPAddress, sizeof (users[i].theUDPAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } } printf("# ...sent login notification to user %04i...\n", users[i].clientID); } printf("# ...finished sending login notifications.\n"); if (userIndex < 0) { //if the user doesn't exist, set user to logged in userIndex = numUsers; //if data structure is at capacity if (numUsers == userLimit) { //increment the user limit userLimit += INCREMENT_USERS; //alloc more space users = realloc(users, sizeof (Client) * userLimit); } } //sets the user to logged in users[userIndex].isLoggedIn = true; //gets user id/address users[userIndex].theUDPAddress = theClientAddress; users[userIndex].theTCPAddress = incoming.theAddress; users[userIndex].clientID = incoming.senderID; numUsers++; outgoing.type = TAG_WHO; printf("# Sending WHO result to user %04i...\n", incoming.senderID); //sends who result to newly logged in user for (i = 0; i < numUsers; i++) { if (users[i].isLoggedIn && users[i].clientID != incoming.senderID) { sprintf(outgoing.data, "%04d", users[i].clientID); //inserts the user id into a string to send to all the other users if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...sent user %04i to %04i...\n", users[i].clientID, incoming.senderID); } } //after all logged in user ids are delivered, send exit message outgoing.confirm = false; //the user has logged out if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...sent final message to user %04i.\n", incoming.senderID); fflush(stdout); break; case TAG_LOGOUT: recvfrom(theSocket, &incoming, sizeof (incoming), 0, (struct sockaddr *) &theClientAddress, &clientAddressLength); fflush(stdout); printf("\n# Received LOGOUT message from %04i.\n", incoming.senderID); //LOGOUT, removes the user from the list of logged out users, sends a message to each other user that the user logged out outgoing.type = TAG_LOGOUT; //the outgoing message type is logout outgoing.confirm = true; //the user has logged out outgoing.senderID = SERVER_ID; sprintf(outgoing.data, "%d", incoming.senderID); //inserts the user id into a string to send to all the other users printf("# Sending logout notifications...\n"); //sends message to all users that the user logged out for (i = 0; i < numUsers; i++) { if (users[i].isLoggedIn && users[i].clientID != incoming.senderID) { if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &users[i].theUDPAddress, sizeof (users[i].theUDPAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...sent logout notification to user %04i...\n", users[i].clientID); } } printf("# ...finished sending logout notifications.\n"); //actually logs out the user userIndex = getUserIndex(incoming.senderID, numUsers, users); users[userIndex].isLoggedIn = false; printf("# User %04i logged out.\n", incoming.senderID); fflush(stdout); break; case TAG_WHO: recvfrom(theSocket, &incoming, sizeof (incoming), 0, (struct sockaddr *) &theClientAddress, &clientAddressLength); fflush(stdout); printf("\n# Received WHO request from user %04i...\n", incoming.senderID); //WHO, returns to the user a list of all of the currently logged in users outgoing.type = TAG_WHO; //the outgoing message type is logout outgoing.confirm = true; //the user has logged out outgoing.senderID = SERVER_ID; //to user the list of all logged in users for (i = 0; i < numUsers; i++) { if (users[i].isLoggedIn && users[i].clientID != incoming.senderID) { sprintf(outgoing.data, "%04d", users[i].clientID); //inserts the user id into a string to send to all the other users if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...sent user %04i to %04i...\n", users[i].clientID, incoming.senderID); } } //after all logged in user ids are delivered, send exit message outgoing.confirm = false; //the user has all of the dudes if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...sent final message to user %04i.\n", incoming.senderID); fflush(stdout); break; case TAG_TALK_REQ: recvfrom(theSocket, &incoming, sizeof (incoming), 0, (struct sockaddr *) &theClientAddress, &clientAddressLength); fflush(stdout); printf("\n# Received TALK request from user %04i to speak with %04i...\n", incoming.senderID, atoi(incoming.data)); userIndex = getUserIndex(atoi(incoming.data), numUsers, users); if (userIndex >= 0) { if (incoming.senderID == users[userIndex].clientID) { outgoing.confirm = false; printf("# ...user %04i attempted to communicate with their self...\n", atoi(incoming.data)); } else { // outgoing.theAddress = incoming.theAddress; // outgoing.senderID = incoming.senderID; // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &theClientAddress, // sizeof (theClientAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } outgoing.senderID = SERVER_ID; outgoing.theAddress = users[userIndex].theTCPAddress; outgoing.theOtherAddress = users[userIndex].theUDPAddress; outgoing.confirm = true; printf("# ...assigning user %04i's address (%i) to out going message...\n", users[userIndex].clientID, users[userIndex].theTCPAddress.sin_port); } } else { outgoing.confirm = false; printf("# ...unable to find user %04i...\n", atoi(incoming.data)); } outgoing.type = TAG_TALK_RES; outgoing.senderID = SERVER_ID; if (sendto(theSocket, &outgoing, sizeof (outgoing), 0, (struct sockaddr *) &theClientAddress, sizeof (theClientAddress)) != sizeof (outgoing)) { dieWithError("sendto() sent a different number of bytes than expected"); } printf("# ...sending address of %04i to %04i.\n", atoi(incoming.data), incoming.senderID); fflush(stdout); // if (*handlingTalk == false) { // processID = fork(); // if (processID == 0) { // *handlingTalk = true; // recvfrom(theSocket, &incoming, sizeof (incoming), 0, // (struct sockaddr *) &theClientAddress, &clientAddressLength); // fflush(stdin); // printf("# Received TALK request from user %04i...\n", incoming.senderID); // //TALK, sends a request to start talking with a user // outgoing.type = TAG_WHO; //the outgoing message type is logout // outgoing.confirm = true; //the user has logged out // // userIndex = getUserIndex(incoming.senderID, numUsers, users); // //sends message to all users that the new user logged in // for (i = 0; i < numUsers; i++) { // if (users[i].isLoggedIn) { // sprintf(outgoing.data, // "%04d", // users[i].clientID); //inserts the user id into a string to send to all the other users // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &theClientAddress, // sizeof (theClientAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } // printf("# ...sent user %04i to %04i...\n", users[i].clientID, incoming.senderID); // } // } // // //after all logged in user ids are delivered, send exit message // outgoing.confirm = false; //the user has logged out // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &theClientAddress, // sizeof (theClientAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } // printf("# ...sent final message to user %04i...\n", incoming.senderID); // // for (;;) { // recvfrom(theSocket, &incoming, sizeof (incoming), MSG_PEEK, // (struct sockaddr *) &theClientAddress, &clientAddressLength); // printf("# in id: %i | type: %i\n", incoming.type, TAG_TALK_REQ); // printf("# in id: %i | u id: %i\n", incoming.senderID, users[userIndex].clientID); // if (incoming.type == TAG_TALK_REQ && incoming.senderID == users[userIndex].clientID) { // //receive user request // recvfrom(theSocket, &incoming, sizeof (incoming), 0, // (struct sockaddr *) &theClientAddress, &clientAddressLength); // break; // } // } // // j = atoi(incoming.data); // printf("# ...received request to communicate with the number %i logged in user...\n", j); // if (j > numUsers) { // outgoing.type = TAG_TALK_RES; // outgoing.confirm = false; // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &users[i].theUDPAddress, // sizeof (users[i].theUDPAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } // printf("# ...user %04i attempted to talk to someone beyond limit.\n", incoming.senderID); // } else { // for (i = 0; i < numUsers; i++) { // if (users[i].isLoggedIn) { // j--; // if (j == 0) { // if (users[i].clientID == incoming.senderID) { // outgoing.type = TAG_TALK_RES; // outgoing.confirm = false; // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &users[i].theUDPAddress, // sizeof (users[i].theUDPAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } // printf("# ...user %04i attempted to talk to their self.\n", incoming.senderID); // } else { // outgoing.type = TAG_TALK_REQ; // outgoing.theAddress = theClientAddress; // outgoing.senderID = incoming.senderID; // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &users[i].theUDPAddress, // sizeof (users[i].theUDPAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } // printf("# ...sent request from user %04i to %04i...\n", incoming.senderID, users[i].clientID); // } // break; // } // } // } // } // // if (j >= 0) { // for (;;) { // recvfrom(theSocket, &incoming, sizeof (incoming), MSG_PEEK, // (struct sockaddr *) &theClientAddress, &clientAddressLength); // printf("# in type: %i | type: %i\n", incoming.type, TAG_TALK_RES); // printf("# in id: %5i | u id: %i\n", incoming.senderID, users[i].clientID); // if (incoming.type == TAG_TALK_RES && incoming.senderID == users[i].clientID) { // //receive other user response // recvfrom(theSocket, &incoming, sizeof (incoming), 0, // (struct sockaddr *) &theClientAddress, &clientAddressLength); // // printf("# ...received %s response from user %i...\n", incoming.confirm == true ? "true" : "false", incoming.senderID); // break; // } // } // // outgoing.type = TAG_TALK_RES; // outgoing.senderID = users[i].clientID; // outgoing.confirm = incoming.confirm; // outgoing.theAddress = users[i].theTCPAddress; // // if (sendto(theSocket, // &outgoing, // sizeof (outgoing), // 0, // (struct sockaddr *) &users[userIndex].theUDPAddress, // sizeof (users[userIndex].theUDPAddress)) // != sizeof (outgoing)) { // dieWithError("sendto() sent a different number of bytes than expected"); // } // } // // // outgoing.senderID = SERVER_ID; // fflush(stdin); // *handlingTalk = false; // // kill(0, SIGTERM); //exits the program // } else { // sleep(2); // } // } break; default: //not gonna happen break; } puts(""); } } else { //forking() no good dieWithError("fork() failed"); } return (EXIT_SUCCESS); }
int main(int argc, char** argv){ int sockfd,multicastfd,multicastfdRecv; struct sockaddr_in serverAddr; struct sockaddr_in multicastAddr; struct sockaddr_in multicastSendAddr; int serverLen,multicastSendAddrLen; char sendLine[1000] = "Send Group Info"; char recvLine[1000]; char senderIP[20]; int on = 1; group grpArr[100]; if (argc != 2) { dieWithError("Usage: Client <Server Port Number>\n"); } memset(&serverAddr, 0, sizeof(serverAddr)); fillAddrStructure(&serverAddr,atoi(argv[1]), NULL); serverAddr.sin_addr.s_addr = INADDR_BROADCAST; serverLen = sizeof(serverAddr); sockfd = socket(AF_INET,SOCK_DGRAM,0); if(sockfd < 0) dieWithError("SockFd"); setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); printf("Sending the request to server for Group information\n"); int n = 15; n = sendto(sockfd, sendLine, n, 0 , (struct sockaddr *)&serverAddr, serverLen); if(n<0) dieWithError("send: "); n = recvfrom(sockfd, recvLine, 1000, 0 , NULL, NULL); char* itr1,*itr2,*itr3; itr1 = recvLine; int i=0; printf("Groups to join\n"); while (itr1!=NULL) { itr2 = strsep(&itr1,"\n"); if(strlen(itr2)<=0) break; printf("%d. %s\n",i+1,itr2); itr3 = strsep(&itr2," "); strcpy(grpArr[i].groupName,itr3); itr3 = strsep(&itr2," "); strcpy(grpArr[i].groupIp,itr3); itr3 = strsep(&itr2," "); strcpy(grpArr[i].groupPort,itr3); i++; } printf("Enter the choise: "); scanf("%d",&n); n--; struct ip_mreq mreq; fillAddrStructure(&multicastAddr, atoi(grpArr[n].groupPort),NULL); multicastfd = socket(AF_INET,SOCK_DGRAM,0); if(multicastfd < 0) dieWithError("SockFd"); //reciever multicastfdRecv = multicastfd; bind(multicastfdRecv,(struct sockaddr*)&multicastAddr,sizeof(multicastAddr)); mreq.imr_multiaddr.s_addr = inet_addr(grpArr[n].groupIp); mreq.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(multicastfdRecv, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { dieWithError("Setsockopt: "); } //------ //sender multicastAddr.sin_addr.s_addr = inet_addr(grpArr[n].groupIp); //----- fd_set allset,rset,wset; int maxfd; FD_ZERO(&allset); FD_SET(STDIN_FILENO,&allset); FD_SET(multicastfdRecv,&allset); printf("Enter the message to send: "); fflush(stdout); //if(fcntl(STDIN_FILENO,F_SETFL,O_NONBLOCK)<0) // dieWithError("fcntl:"); maxfd = multicastfd+1; while (1) { rset = allset; select(maxfd,&rset,NULL,NULL,NULL); if (FD_ISSET(STDIN_FILENO,&rset)) { memset(sendLine,0,1000); n = read(STDIN_FILENO,sendLine,1000); sendLine[n-1]='\0'; //printf("->>%s\n",sendLine); sendto(multicastfd,sendLine,n,0,(struct sockaddr*)&multicastAddr,sizeof(multicastAddr)); // perror("Sendto issue: "); printf("Enter the message to send: "); fflush(stdout); }else if (FD_ISSET(multicastfdRecv,&rset)) { multicastSendAddrLen = sizeof(multicastSendAddr); memset(recvLine,0,1000); recvfrom(multicastfdRecv,recvLine,1000,0,(struct sockaddr*)&multicastSendAddr,&multicastSendAddrLen); //printf("->>%s\n",recvLine); inet_ntop(AF_INET,&(multicastSendAddr.sin_addr),&senderIP,multicastSendAddrLen); printf("Message-> %s :: from: %s\n",recvLine,senderIP); fflush(stdout); } } }