-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.c
98 lines (92 loc) · 2.41 KB
/
test.c
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
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
int server_sockfd, client_sockfd;
int state, client_len;
int pid;
FILE *fp;
struct sockaddr_in clientaddr, serveraddr;
char buf[255];
char line[255];
if (argc != 2)
{
printf("Usage : ./zipcode [port]\n");
printf("예 : ./zipcode 4444\n");
exit(0);
}
memset(line, '0', 255);
state = 0;
// 주소 파일을 읽어들인다.
client_len = sizeof(clientaddr);
if((fp = fopen("zipcode.txt", "r")) == NULL)
{
perror("file open error : ");
exit(0);
}
// internet 기반의 소켓 생성 (INET)
if ((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket error : ");
exit(0);
}
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(atoi(argv[1]));
state = bind(server_sockfd , (struct sockaddr *)&serveraddr,
sizeof(serveraddr));
if (state == -1)
{
perror("bind error : ");
exit(0);
}
state = listen(server_sockfd, 5);
if (state == -1)
{
perror("listen error : ");
exit(0);
}
while(1)
{
client_sockfd = accept(server_sockfd, (struct sockaddr *)&clientaddr,
&client_len);
if (client_sockfd == -1)
{
perror("Accept error : ");
exit(0);
}
while(1)
{
rewind(fp);
memset(buf, '0', 255);
if (read(client_sockfd, buf, 255) <= 0)
{
close(client_sockfd);
break;
}
if (strncmp(buf, "quit",4) == 0)
{
write(client_sockfd, "bye bye", 8);
close(client_sockfd);
break;
}
//while(fgets(line,255,fp) != NULL)
//{
// if (strstr(line, buf) != NULL)
// write(client_sockfd, line, 255);
// memset(line, '0', 255);
//}
write(client_sockfd, "end", 255);
printf("send end\n");
}
}
close(client_sockfd);
}