/* client.c -- client TCP program, adapted from Comer's book */ /* usage: client hostname portnumber */ /* compile cc cli.c -lsocket -lnsl, at least on solaris */ #ifndef unix #define WIN32 #include #include #else #include #include #include #include #endif #include #include #include main(int argc, char *argv[]) { struct hostent *ptrh; /* host table entry */ struct protoent *ptrp; /* protocol table entry */ struct sockaddr_in sad; /* server adr */ int sd; int port = 5194; /* default port */ char *host = "localhost"; /* default hostname */ char buf[50000], buf2[50000]; /* SLEAZE! */ int i, n; memset((char *) &sad, 0, sizeof(sad)); sad.sin_family = AF_INET; /* internet */ if (argc > 2) port = atoi(argv[2]); sad.sin_port = htons((u_short) port); if (argc > 1) host = argv[1]; fprintf(stderr, "starting C client calling %s %d\n", host, port); if ((ptrh = gethostbyname(host)) == NULL) { fprintf(stderr, "invalid host %s\n", host); exit(1); } memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length); if ((ptrp = getprotobyname("tcp")) == NULL) { fprintf(stderr, "can't map TCP to protocol number\n"); exit(1); } if ((sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto)) < 0) { fprintf(stderr, "socket creation failed\n"); exit(1); } if (connect(sd, (struct sockaddr *) &sad, sizeof(sad)) < 0) { fprintf(stderr, "connect failed\n"); exit(1); } while (fgets(buf, sizeof(buf), stdin) != NULL) { /* read client stdin */ sprintf(buf2, "%s", buf); write(sd, buf2, strlen(buf2)); fprintf(stderr, "cli sent [%s]\n", buf2); /* read replies from server */ for (i = 0; (n = read(sd, buf+i, 1)) == 1; i++) { if (buf[i] == '\n') break; } buf[i] = 0; printf("cli rcvd: {%s}\n", buf); fflush(stdout); if (strcmp("exit\n", buf2) == 0) break; } close(sd); exit(0); }