#include #include #include #include #include #include #include #include using namespace std; const string MYPORT {"10000"}; const string HOSTNAME{"mirkwood.cs.edinboro.edu"}; const size_t BUFFER_SIZE{1000}; int main() { srand(time(nullptr)); char buffer[BUFFER_SIZE]; int theSocket; // begin new code 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; } // end new code. // this was changed. theSocket = socket(AF_INET, SOCK_DGRAM, 0); if(theSocket == -1) { perror("Socket failed: "); exit(1); } // begin new code // I am just going to assume IPv4 sockaddr * ptr = reinterpret_cast(res->ai_addr); // end new code if( -1 == bind(theSocket, ptr, sizeof(sockaddr_in))) { perror("Bind failed: "); } bool done{false}; socklen_t len; size_t bytes; while (not done) { // sockaddr_un changed to sockaddr_in in both len = sizeof(sockaddr_in); sockaddr_in clientAddress; memset(&buffer, 0, BUFFER_SIZE); bytes = recvfrom(theSocket, buffer, BUFFER_SIZE, 0, reinterpret_cast(&clientAddress), &len); cout << "Got " << bytes << " bytes." << endl; if (bytes > 0) { buffer[bytes-1] = 0; stringstream s(buffer); int number; if (s >> number) { int value = rand() % number+1; // 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 { // reset becuase I used it in the previous if. s.clear(); string word; s >> word; if (word == "quit") { done = true; } else { // send the message back bytes= sendto(theSocket, buffer, bytes, 0, reinterpret_cast(&clientAddress), len); } } } } freeaddrinfo(res); close(theSocket); }