#include #include #include #include #include #include #include #include #include #include #define PORT 4000 #define SERVERHOST "mud.fataldimensions.org" void init_sockaddr (struct sockaddr_in *name, const char *hostname, uint16_t port) { struct hostent *hostinfo; name->sin_family = AF_INET; name->sin_port = htons (port); hostinfo = gethostbyname (hostname); if (hostinfo == NULL) { fprintf (stderr, "Unknown host %s.\n", hostname); exit (EXIT_FAILURE); } name->sin_addr = *(struct in_addr *) hostinfo->h_addr; } void write_to_server (int filedes, char *buff) { int nbytes; nbytes = write (filedes, buff, strlen (buff)+1); if (nbytes < 0) { perror ("write"); exit (EXIT_FAILURE); } } int input_timeout (int filedes, unsigned int seconds); void read_from_server (int filesrc) { int nbytes; char buff[65]; buff[64] = 0; while( input_timeout (filesrc, 5) ) { nbytes = read (filesrc, buff, 64); buff[nbytes] = 0; printf("#%d$%s", nbytes, buff); } } /* Set the O_NONBLOCK flag of desc if value is nonzero, or clear the flag if value is 0. Return 0 on success, or -1 on error with errno set. */ int set_nonblock_flag (int desc, int value) { int oldflags = fcntl (desc, F_GETFL, 0); /* If reading the flags failed, return error indication now. */ if (oldflags == -1) return -1; /* Set just the flag we want to set. */ if (value != 0) oldflags |= O_NONBLOCK; else oldflags &= ~O_NONBLOCK; /* Store modified flag word in the descriptor. */ return fcntl (desc, F_SETFL, oldflags); } int input_timeout (int filedes, unsigned int seconds) { fd_set set; struct timeval timeout; /* Initialize the file descriptor set. */ FD_ZERO (&set); FD_SET (filedes, &set); /* Initialize the timeout data structure. */ timeout.tv_sec = seconds; timeout.tv_usec = 0; /* select returns 0 if timeout, 1 if input available, -1 if error. */ return select (FD_SETSIZE, &set, NULL, NULL, &timeout); } int main (void) { int sock; int nbytes; struct sockaddr_in servername; char linebuffer[300]; printf("\ncreate\n"); /* Create the socket. */ sock = socket (PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror ("socket (client)"); exit (EXIT_FAILURE); } printf("connect\n"); /* Connect to the server. */ init_sockaddr (&servername, SERVERHOST, PORT); if (0 > connect (sock, (struct sockaddr *) &servername, sizeof (servername))) { perror ("connect (client)"); exit (EXIT_FAILURE); } do { read_from_server(sock); scanf("%s", linebuffer); printf(":%s:\n", linebuffer); write_to_server (sock, linebuffer); fprintf (stderr, "select returned %d.\n", input_timeout(sock, 5)); } while(1); close (sock); exit (EXIT_SUCCESS); }