(original) (raw)
/* * echoclient.c - A simple (updated) connection-based client * usage: echoclient */ #include #include #include #include #include #include #include #include #define BUFSIZE 1024 /* error - wrapper for perror */ void error(char *msg) { perror(msg); exit(1); } int main(int argc, char **argv) { int sockfd, n, status; struct addrinfo hints; struct addrinfo *servinfo; /* will point to the getaddrinfo results */ char *hostname, *portno, *res; char buf[BUFSIZE]; /* check command line arguments */ if (argc != 3) { fprintf(stderr,"usage: %s \n", argv[0]); exit(1); } hostname = argv[1]; portno = argv[2]; /* set up struct for getaddrinfo */ memset(&hints, 0, sizeof(hints)); /* make sure the struct is empty */ hints.ai_family = AF_INET; /* use IPv4 */ hints.ai_socktype = SOCK_STREAM; /* use TCP */ /* get ready to connect to server, fill in addrinfo structs*/ status = getaddrinfo(hostname, portno, &hints, &servinfo); if (status) { fprintf(stderr,"ERROR, no such host as %s.\n", hostname); exit(1); } /* make a socket */ sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol); if (sockfd < 0) { error("ERROR opening socket."); } /* connect to server! */ if (connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) < 0) { error("ERROR connecting."); } /* get message line from the user */ printf("Enter msg: "); /* read input: get line from stdin */ memset(buf, 0, BUFSIZE); res = fgets(buf, BUFSIZE, stdin); if (res == NULL) { error("ERROR reading from stdin."); } /* send to server: send the message line to the server */ n = send(sockfd, buf, strlen(buf), 0); if (n < 0) { printf("ERROR writing to socket"); exit(1); } /* recv from server: read and print the server's reply */ memset(buf, 0, BUFSIZE); n = recv(sockfd, buf, BUFSIZE, 0); if (n < 0) { error("ERROR reading from socket."); } printf("Echo reply from server: %s", buf); close(sockfd); freeaddrinfo(servinfo); return 0; }