// Run like this: simple_client address port // Results in argv ["./simple_client", "address", "port"] #include #include #include #include #include #include #include #include #include using namespace std; struct lurk_game_message { uint8_t type; uint16_t initial_points, stat_limit, description_length; char *description = 0; bool read(int skt) { ssize_t readlen = recv(skt, this, 7, MSG_WAITALL); printf("readlen = %d\n", readlen); if(readlen < 7){ printf("Failed to read first 7 bytes, giving up!\n"); return false; } description = (char*)malloc(description_length); readlen = recv(skt, description, description_length, MSG_WAITALL); if(readlen != description_length){ printf("Failed to read description, giving up\n"); free(description); description = 0; return false; } return true; } ~lurk_game_message(){ if(description) free(description); } } __attribute__((packed)); // Otherwise the compiler will leave padding ostream& operator<<(ostream& out, const lurk_game_message &lgm){ out << "Type: " << (int)lgm.type << endl; out << "Initial Points: " << lgm.initial_points << endl; out << "Stat Limit: " << lgm.stat_limit << endl; out << "Description Length: " << lgm.description_length << endl; out << "Description: " << lgm.description << endl; return out; } int main(int argc, char ** argv){ if(argc < 3){ printf("Usage: %s hostname port\n", argv[0]); return 1; } struct sockaddr_in sad; sad.sin_port = htons(atoi(argv[2])); sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // do a dns lookup struct hostent* entry = gethostbyname(argv[1]); if(!entry){ if(h_errno == HOST_NOT_FOUND){ printf("This is our own message that says the host wasn't found\n"); } herror("gethostbyname"); return 1; } struct in_addr **addr_list = (struct in_addr**)entry->h_addr_list; struct in_addr* c_addr = addr_list[0]; char* ip_string = inet_ntoa(*c_addr); sad.sin_addr = *c_addr; // copy the address we found into sad // Finally done with DNS! printf("Connecting to: %s\n", ip_string); if( connect(skt, (struct sockaddr*)&sad, sizeof(struct sockaddr_in)) ){ perror("connect"); return 1; } /* This part would read a version uint8_t message[64]; ssize_t actual_length = recv(skt, message, 5, MSG_WAITALL); if(message[0] == 14) printf("Received %ld bytes: type %d, version %d.%d\n", actual_length, message[0], message[1], message[2]); else printf("Got %d which is not a version\n", message[0]); */ // Method 4: A class with a read method struct lurk_game_message lgm; lgm.read(skt); cout << lgm << endl; close(skt); return 0; }