// 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 #include #include void handle_alarm(int signum){ // printf("beep\n"); } 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)) ){ printf("%d\n", errno); return 1; } // Set up timer to keep waking us up struct sigaction alarm_action; alarm_action.sa_handler = handle_alarm; sigaction(SIGALRM, &alarm_action, 0); struct itimerval our_timerval = { .it_interval = {0, 1000}, .it_value = {0, 1000} }; setitimer(ITIMER_REAL, &our_timerval, 0); printf("EINTR = %d\n", EINTR); char recv_buffer[2048]; char write_buffer[2048]; ssize_t recv_length; ssize_t write_length; while(1){ recv_length = recv(skt, recv_buffer, 2047, MSG_DONTWAIT); if(recv_length > 0){ recv_buffer[recv_length] = 0; printf(recv_buffer); } else { // This works, but only after a couple tries if(recv_length == 14) // We observed the 14, but didn't go find it in the headers break; } write_length = read(0, write_buffer, 2048); write(skt, write_buffer, write_length); } close(skt); return 0; }