-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck5
More file actions
115 lines (97 loc) · 2.46 KB
/
check5
File metadata and controls
115 lines (97 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
Script started on 2020년 11월 02일 (월) 오후 06시 47분 37초
[?1034hnetpa15@~/ 717$ cat p[K[Kprog/tcp_talkserv.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAXLINE 511
char *EXIT_STRING="exit";
int recv_and_print(int sd);
int input_and_send(int sd);
int main(int argc, char *argv[]){
int s,nbyte;
struct sockaddr_in cliaddr, servaddr;
int listen_sock,accp_sock,addrlen=sizeof(cliaddr);
pid_t pid;
int i;
char buf[MAXLINE+1];
if (argc !=2){
printf("Usage: %s hostname\n",argv[0]);
exit(0);
}
if((listen_sock=socket(PF_INET,SOCK_STREAM,0))<0){
perror("socket fail");
exit(0);
}
bzero((char*)&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(atoi(argv[1]));
if(bind(listen_sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0){
perror("bind fail");
exit(0);
}
puts("서버가 클라이언트를 기다리고 있습니다.");
listen(listen_sock,1);
if((accp_sock=accept(listen_sock,(struct sockaddr*)&cliaddr,&addrlen))<0){
perror("accept fail");
exit(0);
}
puts("클라이언트가 연결되었습니다");
if((pid=fork())>0)
input_and_send(accp_sock);
else if(pid==0)
recv_and_print(accp_sock);
close(listen_sock);
close(accp_sock);
return 0;
}
int input_and_send(int sd) {
char buf[MAXLINE + 1];
int nbyte;
while(fgets(buf, sizeof(buf), stdin) != NULL) {
nbyte = strlen(buf);
write(sd,buf,strlen(buf));
if (strstr(buf,EXIT_STRING)!=NULL){
puts("Good bye.");
close(sd);
exit(0);
}
}
return 0;
}
int recv_and_print(int sd) {
char buf[MAXLINE + 1];
int nbyte;
while(1) {
if((nbyte = read(sd, buf, MAXLINE)) < 0) {
perror("read fail");
close(sd);
exit(0);
}
buf[nbyte] = 0;
if(strstr(buf, EXIT_STRING) != NULL) {
break;
}
printf("%s", buf);
}
return 0;
}
netpa15@~/ 718$ ./prog/tcp_tak[Klkcli 117.17.142.162 6015
2017301004
successful receive
next
exit
Good bye
^C
netpa15@~/ 719$ ls -l prog/tcp_talk*
-rwxr-xr-x. 1 netpa15 student 13600 11월 2 11:39 prog/tcp_talkcli
-rw-r--r--. 1 netpa15 student 1466 11월 2 11:39 prog/tcp_talkcli.c
-rwxr-xr-x. 1 netpa15 student 13632 11월 2 10:55 prog/tcp_talkserv
-rw-r--r--. 1 netpa15 student 1769 11월 2 10:55 prog/tcp_talkserv.c
netpa15@~/ 720$ exit
Script done on 2020년 11월 02일 (월) 오후 06시 50분 46초