/*---------------------------------------------------------------------------------------------- ÆÄÀϸí : myecho.c ±â ´É : echo ¼­ºñ½º¸¦ ¿ä±¸ÇÏ´Â TCP(¿¬°áÇü) Ŭ¶óÀ̾ðÆ® ÄÄÆÄÀÏ : cc -o myecho myecho.c -lsocket -lnsl ½ÇÇ࿹ : myecho 203.252.65.3 ----------------------------------------------------------------------------------------------*/ #include #include #include #include #include #define BUF_LEN 128 int main(int argc, char *argv[]) { int s, n, len_in, len_out; struct sockaddr_in server_addr; char *haddr; char buf[BUF_LEN+1]; if(argc != 2) { printf("usage: %s ip_address\n", argv[0]); return -1; } haddr = argv[1]; if((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("can't create socket\n"); return -1; } if((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("can't create socket\n"); return -1; } /* echo ¼­¹öÀÇ ¼ÒÄÏÁÖ¼Ò ±¸Á¶Ã¼ ÀÛ¼º */ bzero((char *)&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(haddr); server_addr.sin_port = htonl(7); /* ¿¬°á¿äû */ if(connect(s, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { printf("can't connect.\n"); return -1; } /* Å°º¸µå ÀÔ·ÂÀ» ¹ÞÀ½ */ printf("Input any string : "); if (fgets(buf, BUF_LEN, stdin)) { buf[BUF_LEN] = '\0'; len_out = strlen(buf); } else { printf("fgets error\n"); return -1; } /* echo ¼­¹ö·Î ¸Þ½ÃÁö ¼Û½Å */ if (write(s, buf, len_out) < 0) { printf("write error\n"); return -1; } /* ¼ö½ÅµÈ echo ¸Þ½ÃÁö È­¸éÃâ·Â */ printf("Echoed string : "); for(len_in=0,n = 0; len_in < len_out; len_in += n) { if((n = read(s, &buf[len_in], len_out - len_in)) < 0) { printf("read error\n"); return -1; } } printf("%s", buf); close(s); }