00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #include <stdio.h>
00013 #include <string.h>
00014 #include <sys/types.h>
00015 #include <sys/socket.h>
00016 #include <netinet/in.h>
00017 #include <netdb.h>
00018
00019 #define PORT 54321
00020 #define BUFSIZE 512
00021
00022 main(int argc, char **argv)
00023 {
00024 struct sockaddr_in addr;
00025 struct hostent *hp;
00026 int fd;
00027 int len;
00028 char buf[BUFSIZE];
00029 int ret;
00030
00031 if (argc != 2){
00032 printf("Usage: echo_client hostname\n");
00033 exit(1);
00034 }
00035
00036 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
00037 perror("socket");
00038 exit(1);
00039 }
00040
00041 if ((hp = gethostbyname(argv[1])) == NULL) {
00042 perror("gethostbyname");
00043 exit(1);
00044 }
00045
00046 memset((void*)&addr, 0, sizeof(addr));
00047 memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
00048
00049 addr.sin_family = AF_INET;
00050 addr.sin_port = htons(PORT);
00051
00052 if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0){
00053 perror("connect");
00054 exit(1);
00055 }
00056
00057 while (fgets(buf, BUFSIZE, stdin) != NULL) {
00058
00059 int len = strlen(buf) + 1;
00060
00061 ret = write(fd, buf, len);
00062 if (ret != len) {
00063 perror("write");
00064 close(fd);
00065 exit(1);
00066 }
00067
00068 ret = read(fd, buf, len);
00069 if (ret != len) {
00070 perror("read");
00071 close(fd);
00072 exit(1);
00073 }
00074
00075 buf[ret] = '\0';
00076 printf("%s", buf);
00077 }
00078
00079 close(fd);
00080 exit(0);
00081 }