// Run like this: simple_client address port // Results in argv ["./simple_client", "address", "port"] #include #include #include #include #include #include #include #include #include #include #include #include void *recv_thread(void *p){ int skt = *(int*)p; char recv_buffer[2048]; while(1){ if(recv(skt, recv_buffer, 2048, 0) < 1) break; printf(recv_buffer); } printf("recv_thread terminating, probable disconnect\n"); return 0; } 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; } pthread_t recv_thread_handle; pthread_create(&recv_thread_handle, 0, recv_thread, &skt); while(1){ char *cmdbuffer = readline(""); if(!cmdbuffer) // User hit ctrl+d break; if(!*cmdbuffer) // Got an empty line continue; add_history(cmdbuffer); write(skt, cmdbuffer, strlen(cmdbuffer)); free(cmdbuffer); } close(skt); return 0; }