27 he
=gethostbyname(host
);
30 memcpy(&ip
, he
->h_addr_list
[0],he
->h_length
);
36 bind_interface(int fd
, unsigned int ip
, int port
)
38 struct sockaddr_in sin
;
40 memset(&sin
,0,sizeof(sin
));
41 sin
.sin_family
= AF_INET
;
42 sin
.sin_addr
.s_addr
=ip
;
43 sin
.sin_port
= htons((unsigned short) port
);
44 if (bind(fd
, (struct sockaddr
*) &sin
,sizeof(sin
)) < 0)
51 set_nonblocking(int fd
)
55 if (ioctlsocket (fd
, FIONBIO
, &val
) != 0)
57 if (fcntl (fd
, F_SETFL
, O_NONBLOCK
) != 0)
65 tcp_socket(char *host
, int port
, int type
)
67 struct sockaddr_in sin
;
70 memset(&sin
,0,sizeof(sin
));
71 sin
.sin_family
= AF_INET
;
72 sin
.sin_port
= htons((unsigned short)port
);
73 sin
.sin_addr
.s_addr
= host
? lookup_ip(host
):htonl(INADDR_ANY
);
75 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
79 bind(sock
, (struct sockaddr
*) &sin
,sizeof(sin
));
81 connect(sock
, (struct sockaddr
*) &sin
,sizeof(sin
));
87 readn(int fd
, void *vptr
, size_t n
)
95 if ((nread
= read(fd
, p
, nleft
)) < 0)
110 writen(int fd
, void *vptr
, size_t n
)
118 if ((nread
= write(fd
, p
, nleft
)) < 0)
132 unsigned char Buf
[2048];
135 send_cmd (int fd
, unsigned int cmd
, const char *fmt
, ...)
142 vsnprintf (Buf
+ 4, sizeof (Buf
) - 4, fmt
, ap
);
145 l
= strlen (Buf
+ 4);
150 memcpy(Buf
+2, &s
, 2);
152 writen (fd
, Buf
, 4 + l
);
154 printf("SEND:[%d,%d] %s\n",cmd
, l
, Buf
+4);
157 #define HANDLER(f) void f (int fd, unsigned int cmd, char *pkt, unsigned int len)
162 HANDLER ((*handler
));
166 split_line(char **av
, char *pkt
, int max
)
170 while(*pkt
&& n
< max
)
172 while(*pkt
==' ') pkt
++;
174 while(*pkt
==' ') pkt
++;
179 /* <name> <runs> <len1> [<len2> ....] */
180 HANDLER(meta_cipher_process
)
186 ac
= split_line(av
, pkt
, 32);
190 numPkts
= atoi(av
[1]);
191 for (i
=2; i
< ac
; i
++)
193 if (test_meta_cipher_process(av
[0], numPkts
, atoi(av
[i
]), &swT
, &hwT
))
195 send_cmd(fd
, cmd
, "%s %.2f %.2f", av
[1], swT
, hwT
);
202 {1, meta_cipher_process
},
205 int HNDLR_SIZE
= sizeof(hndls
)/sizeof(hndls
[0]);
208 server_dispatch(int fd
)
215 n
= readn(fd
, Buf
, 4);
218 memcpy(&len
, Buf
, 2);
219 memcpy(&cmd
, Buf
+2, 2);
222 n
= readn(fd
, Buf
, len
);
226 printf("RECV:[%d,%d] %s\n",cmd
, len
, Buf
);
228 for (n
=0; n
< HNDLR_SIZE
; n
++)
229 if (hndls
[n
].cmd
== cmd
)
231 hndls
[n
].handler(fd
, cmd
, Buf
, len
);
240 struct sockaddr_in caddr
;
247 WSAStartup (MAKEWORD (1, 1), &wsa
);
249 sock
= tcp_socket(NULL
,SERVER_PORT
,TCPSERVER
);
251 printf("listen at port %d\n",SERVER_PORT
);
255 fd
= accept(sock
,(struct sockaddr
*) &caddr
,&len
);
258 printf("accept a client at fd %d\n",fd
);
264 #if defined(WIN32) && !defined(__CYGWIN__)