// Run like this: simple_client address port // Results in argv ["./simple_client", "address", "port"] #include #include #include #include #include #include #include #include int main(int argc, char ** argv){ if(argc < 3){ printf("Usage for a query: %s hostname port\n", argv[0]); printf("Usage for a report: %s hostname port number\n", argv[0]); return 1; } uint32_t squirrels = 0; if(argc == 4){ // We must be sending a report squirrels = atoi(argv[3]); if(squirrels == 0) { printf("Can't report 0 squirrels\n"); return 1; } } struct sockaddr_in sad; sad.sin_port = htons(atoi(argv[2])); sad.sin_family = AF_INET; printf("port: %d\n", sad.sin_port); 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; // -> is like (*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; } if(squirrels){ // We're sending a report uint8_t type = 1; printf("Reporting %d squirrels\n", squirrels); write(skt, &type, 1); write(skt, &squirrels, 4); read(skt, &type, 1); if(type == 3) printf("Report was received!\n"); else printf("Report was not received - did we connect to the right server?\n"); } else { // We're sending a query uint8_t type = 2; write(skt, &type, 1); read(skt, &type, 1); if(type == 4){ read(skt, &squirrels, 4); printf("Total is %d squirrels\n", squirrels); } else { printf("Unexpected response %d from server\n", type); } } close(skt); return 0; }