#include #include #include #include #include #include #include int main(){ struct sockaddr_in sad; sad.sin_port = htons(5141); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_DGRAM, 0); bind(skt, (struct sockaddr *)(&sad), sizeof(struct sockaddr_in)); // No listen. We're using UDP char buffer[20]; long int a, b; struct sockaddr_in cad; socklen_t cad_size = sizeof(struct sockaddr_in); for(;;){ recvfrom(skt, buffer, 20, 0, (struct sockaddr*)&cad, &cad_size); a = *(long int*)(buffer+4); b = *(long int*)(buffer+12); buffer[4] = 0; printf("Message from %s was %s, arguments %ld and %ld\n", inet_ntoa(cad.sin_addr), buffer, a, b); if(!strncmp(buffer, "DIVI", 4)) a = a / b; else if (!strncmp(buffer, "MODU", 4)) a = a / b; else { strcpy(buffer, "LAZY"); a = 1; memcpy(buffer+4, &a, 8); sendto(skt, buffer, 12, 0, (struct sockaddr*)&cad, cad_size); printf("Sending LAZY\n"); continue; } strcpy(buffer, "RESL"); memcpy(buffer+4, &a, 8); /* This next line assumes that the client has not sent another request * If they did, and a request or an answer got lost, they could have the wrong answer! * Problem scenario: * Client sends request D * Request D gets lost * Client sends request E * We get request E and reply * The client assumes our answer to E is the answer to E * The client assumes we never answered E, and has the wrong answer to D * * One way to fix it: Include the original question with the answer! * DNS does this * Will make the message bigger * Another way: Include a token (a request number) * This works, but we'll have to track the token * What if somebody steals the token! * Then they can pretend to be us */ sendto(skt, buffer, 12, 0, (struct sockaddr*)&cad, cad_size); printf("Sent RESL\n"); } }