// Run like this: simple_client address port // Results in argv ["./simple_client", "address", "port"] #include #include #include #include #include #include #include #include class version_message { public: uint8_t type, major, minor; uint16_t extlen; void read(int socket){ recv(socket, this, 5, MSG_WAITALL); } void print(){ printf("Got type %d, version %d.%d with %d bytes of extensions\n", type, major, minor, extlen); } }__attribute__((packed)); class game_message { public: uint8_t type; uint16_t initial_points, stat_limit, description_length; char *description = 0; void read(int socket){ recv(socket, this, 7, MSG_WAITALL); description = (char*)malloc(description_length); recv(socket, description, description_length, MSG_WAITALL); } void print(){ printf("Received game (ip: %d sl: %d dl: %d \n%s\n", initial_points, stat_limit, description_length, description); } ~game_message(){ if(description) free(description); } }__attribute__((packed)); 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; } uint8_t type; while(1){ recv(skt, &type, 1, MSG_PEEK); if(type == 14){ version_message v; v.read(skt); v.print(); } else if(type == 11){ game_message g; g.read(skt); g.print(); } else { printf("Unknown type: %d\n", type); break; } } close(skt); return 0; }