#include #include #include #include #include #include #include #include using namespace std; // nc -u -v -4 mirkwood.cs.edinboro.edu 10000 const string MYPORT {"10000"}; const string HOSTNAME{"mirkwood.cs.edinboro.edu"}; const size_t BUFFER_SIZE{1000}; int main([[maybe_unused]] int argc, char * argv[]) { srand(time(nullptr)); char buffer[BUFFER_SIZE]; int theSocket; addrinfo *res; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; int errCode; errCode = getaddrinfo(HOSTNAME.c_str(), MYPORT.c_str() , &hints, &res); if (errCode != 0) { cout << "Get Address Error: " << gai_strerror(errCode) << endl; return 1; } theSocket = socket(AF_INET, SOCK_DGRAM, 0); if(theSocket == -1) { perror("Socket failed: "); exit(1); } sockaddr * ptr = reinterpret_cast(res->ai_addr); if( -1 == bind(theSocket, ptr, sizeof(sockaddr_in))) { perror("Bind failed: "); } freeaddrinfo(res); bool done{false}; socklen_t len; size_t bytes; cout << argv[0] << " started" << endl; // should fix this to use information from getaddrinfo cout << "Connect with nc -u -v -4 147.64.242.52 10000" << endl; cout << "\tinteger input will roll a die" << endl; cout << "\tquit will cause the server to exit " << endl; cout << endl; while (not done) { cout << endl; len = sizeof(sockaddr_in); sockaddr_in clientAddress; memset(&buffer, 0, BUFFER_SIZE); bytes = recvfrom(theSocket, buffer, BUFFER_SIZE, 0, reinterpret_cast(&clientAddress), &len); char nbuffer[100]; inet_ntop(AF_INET, reinterpret_cast (&clientAddress.sin_addr), nbuffer, 100); int port = ntohs(clientAddress.sin_port); cout << "Got " << bytes << " bytes from " << nbuffer << ":" << port << "." << endl; if (bytes > 0) { buffer[bytes-1] = 0; stringstream s(buffer); int number; if (s >> number) { int value{0}; if (number > 0) { value = rand() % number+1; } // should return an error message for 0 and negative cout << "The bytes were the number " << number << ", returning " << value << "." << endl; // create a result to send back stringstream out; out << "The result of d" << number << " is " << value << endl; // just so I dont' have to do a out.str().c_str() string copy = out.str(); memset(&buffer, 0, BUFFER_SIZE); size_t size = min(BUFFER_SIZE, copy.size()+1); strncpy(buffer, copy.c_str(), BUFFER_SIZE-1); bytes= sendto(theSocket, buffer, size, 0, reinterpret_cast(&clientAddress), len); } else { s.clear(); string word; s >> word; cout << "The bytes were the word " << word << endl; if (word == "quit") { done = true; } else { bytes= sendto(theSocket, buffer, bytes, 0, reinterpret_cast(&clientAddress), len); } } } } close(theSocket); return 0; }