729 #include #include #include #include #include #include #include #include #include #include #define PORT 5555 #define MESSAGE "Yow!!! Are we having fun yet?!?" #define SERVERHOST "localhost" void write_to_server (int filedes) { int nbytes; nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1); if (nbytes < 0) { perror ("write"); exit (EXIT_FAILURE); } } int main (void) { struct timeval tv; fd_set fds; int sock, oldstate, curstate, r, err; int optlen = sizeof(int); struct sockaddr_in servername; /* Create the socket. */ sock = socket (PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror ("socket (client)"); exit (EXIT_FAILURE); } oldstate = fcntl(sock, F_GETFL); curstate = oldstate | O_NONBLOCK; r = fcntl(sock, F_SETFL, curstate); if (r < 0) { perror("fcntl"); exit(1); } /* Connect to the server. */ init_sockaddr (&servername, SERVERHOST, PORT); if (0 > connect (sock, (struct sockaddr *) &servername, sizeof (servername))) { perror ("connect (client)"); } FD_ZERO(&fds); FD_SET(sock, &fds); tv.tv_sec = 5; tv.tv_usec = 0; r = select(sock + 1, NULL, &fds, NULL, &tv); while (1) { if (FD_ISSET(sock, &fds)) { getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&err, &optlen); if (err != 0) { perror("getsockopt"); } break; } if (r <= 0) { if (r < 0) perror("select"); else { printf("Timeout %d\n", r); } } } /* Send data to the server. */ write_to_server (sock); close (sock); exit (EXIT_SUCCESS); } . 0