5 int resolve(const char *host
, unsigned short port
, struct addrinfo
** addr
) {
6 struct addrinfo hints
= {
7 .ai_family
= AF_UNSPEC
,
8 .ai_socktype
= SOCK_STREAM
,
9 .ai_flags
= AI_PASSIVE
,
12 snprintf(port_buf
, sizeof port_buf
, "%u", port
);
13 return getaddrinfo(host
, port_buf
, &hints
, addr
);
16 int server_waitclient(struct server
*server
, struct client
* client
) {
17 socklen_t clen
= sizeof client
->addr
;
18 return ((client
->fd
= accept(server
->fd
, (void*)&client
->addr
, &clen
)) == -1)*-1;
21 int server_setup(struct server
*server
, const char* listenip
, unsigned short port
) {
22 struct addrinfo
*ainfo
= 0;
23 if(resolve(listenip
, port
, &ainfo
)) return -1;
26 for(p
= ainfo
; p
; p
= p
->ai_next
) {
27 if((listenfd
= socket(p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) < 0)
30 setsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(int));
31 if(bind(listenfd
, p
->ai_addr
, p
->ai_addrlen
) < 0) {
38 if(listenfd
< 0) return -2;
40 if(listen(listenfd
, SOMAXCONN
) < 0) {
44 server
->fd
= listenfd
;