/* * TCP/IP client program * Usage: ./client host_name */ #include #include #include #include #include #define PORTNO 50001 /* port No. of the socket */ #define BUF_MAX 64 /* the size of the communication buffer */ main(int argc, char *argv[]) { struct sockaddr_in server_addr; /* socket address */ struct hostent *host_entry; /* host address of the server */ int sid; /* session id of the socket */ char buf[BUF_MAX]; /* communication buffer */ /* commandline argument check */ if (argc != 2) { fprintf(stderr, "argument mismatch\n"); exit(1); } /* create a socket */ if ((sid = socket(AF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "could not make a socket\n"); exit(1); } /* get host ip address of the server */ if ((host_entry = gethostbyname(argv[1])) == NULL) { fprintf(stderr, "cold not find host\n"); exit(1); } /* connect */ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORTNO); memcpy((char *)&server_addr.sin_addr, (char *)host_entry->h_addr, host_entry->h_length); if (connect(sid, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { fprintf(stderr, "could not connect to the server\n"); exit(1); } /* send/recv */ if (recv(sid, buf, BUF_MAX, 0) == -1) { fprintf(stderr, "send/recv error\n"); exit(1); } printf("%s\n", buf); /* shutdown and close the socket */ if (shutdown(sid, 2) == -1) { fprintf(stderr, "shutdown error\n"); exit(1); } close(sid); exit(0); }