/********************* client.c ********************* / #include #include #include #include #include #include #include #include #include #define SERVER_IP "127.0.0.1" #define ADDR_LEN (sizeof(struct sockaddr)) #define PORT 20000 extern int errno; int main() { int fd_client; struct sockaddr_in serv_addr; char buf[256]; int check_ret; buf[0] = '\0'; fd_client = socket(AF_INET, SOCK_STREAM, 0); if(fd_client < 0) { printf("error creating socket. errno is %d\n", errno); exit(1); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP); bzero(&(serv_addr.sin_zero), 8); check_ret = connect(fd_client, (struct sockaddr *) &serv_addr, ADDR_LEN); if(check_ret < 0) { printf("Connect error. Errno is %d\n", errno); exit(1); } while(1) { printf("WRITE : "); fgets(buf, 256, stdin); buf[strlen(buf)] = '\0'; check_ret = write(fd_client, buf, 256); if(check_ret < 0) { printf("errno is %d\n", errno); } bzero(buf, 256); printf("READ : "); read(fd_client, buf, 256); printf("%s", buf); bzero(buf, 256); } return 0; } /********************* server.c ********************* / #include #include #include #include #include #include #include #include #define SADDR_LEN (sizeof(struct sockaddr)) #define SERVER_PORT 20000 extern int errno; int main() { int fd_server; int fd_client; struct sockaddr_in serv_address; struct sockaddr_in client_address; char buf[256]; int check_ret; int sockaddr_in_len = (sizeof(struct sockaddr_in)); fd_server = socket(AF_INET, SOCK_STREAM, 0); if(fd_server < 0) { printf("socket error. errno is %d\n", errno); exit(1); } serv_address.sin_family = AF_INET; serv_address.sin_port = htons(SERVER_PORT); serv_address.sin_addr.s_addr = INADDR_ANY; bzero(&(serv_address.sin_zero), 8); check_ret = bind(fd_server, (struct sockaddr *) &serv_address, SADDR_LEN); if(check_ret < 0) { printf("bind error. errno is %d\n", errno); close(fd_server); exit(1); } check_ret = listen(fd_server, 1); if(check_ret < 0) { printf("listen error. errno is %d\n", errno); close(fd_server); exit(1); } fd_client = accept(fd_server, (struct sockaddr *) &client_address, &sockaddr_in_len); while(1) { printf("READ : "); check_ret = read(fd_client, buf, 256); buf[strlen(buf)] = '\0'; if(check_ret > 0) { printf("%s", buf); } bzero(buf, 256); printf("WRITE : "); fgets(buf, 256, stdin); write(fd_client, buf, 256); bzero(buf, 256); } return 0; }