-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysocklib.c
90 lines (72 loc) · 2.28 KB
/
mysocklib.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
#include "net_simplelib.h"
int
server_socket(const char *host,const char *portnum){
int listenfd;
socklen_t addrlen;
listenfd = Tcp_listen(host, portnum, &addrlen);
return (listenfd);
}
void
accept_loop(int soc){
char hbuf[NI_MAXHOST],sbuf[NI_MAXSERV];
struct sockaddr_storage from;
int connfd;
socklen_t len;
for (;;){
len = (socklen_t) sizeof(from);
/* accept connection */
if ((connfd = Accept(soc,(struct sockaddr *) &from ,&len)) == -1){
if (errno != EINTR){
err_print("accept");
}
}else {
(void) getnameinfo((struct sockaddr *) &from ,len,
hbuf,sizeof(hbuf),
sbuf,sizeof(sbuf),
NI_NUMERICHOST | NI_NUMERICSERV);
err_print("accept:%s:%s\n",hbuf,sbuf);
/*send and receive loop*/
send_recv_loop(connfd);
/*accept socket close */
Close(connfd);
connfd = 0;
}
}
}
/* receive and sent loop */
void
send_recv_loop(int acc){
char buf[512],*ptr;
ssize_t len;
for (;;){
/*receive*/
if ((len = recv(acc,buf,sizeof(buf),0)) == -1){
/*erro */
//perror("recv");
err_print("recv");
break;
}
if (len == 0){
/*end of file */
//(void) fprintf(stderr,"recv:EOF\n");
err_print("recv:EOF\n");
break;
}
/* strings make */
buf[len] = '\0';
if ((ptr = strpbrk(buf,"\r\n")) != NULL) {
*ptr = '\0';
}
//(void) fprintf(stderr,"[client]%s\n",buf);
err_print("[client]%s\n",buf);
/* making response strings */
(void)mystrlcat(buf,":Received\r\n",sizeof(buf));
len = (ssize_t) strlen(buf);
Send(acc,buf,(size_t)len,0);
/* if ((len = send(acc,buf,(size_t) len,0)) == -1){ */
/* /\* error *\/ */
/* err_print("send"); */
/* break; */
/* } */
}
}