6 int resolve(const char *host
, unsigned short port
, struct addrinfo
** addr
) {
7 struct addrinfo hints
= {
8 .ai_family
= AF_UNSPEC
,
9 .ai_socktype
= SOCK_STREAM
,
10 .ai_flags
= AI_PASSIVE
,
13 snprintf(port_buf
, sizeof port_buf
, "%u", port
);
14 return getaddrinfo(host
, port_buf
, &hints
, addr
);
17 int resolve_sa(const char *host
, unsigned short port
, union sockaddr_union
*res
) {
18 struct addrinfo
*ainfo
= 0;
20 SOCKADDR_UNION_AF(res
) = AF_UNSPEC
;
21 if((ret
= resolve(host
, port
, &ainfo
))) return ret
;
22 memcpy(res
, ainfo
->ai_addr
, ainfo
->ai_addrlen
);
27 int bindtoip(int fd
, union sockaddr_union
*bindaddr
) {
28 socklen_t sz
= SOCKADDR_UNION_LENGTH(bindaddr
);
30 return bind(fd
, (struct sockaddr
*) bindaddr
, sz
);
34 int server_waitclient(struct server
*server
, struct client
* client
) {
35 socklen_t clen
= sizeof client
->addr
;
36 return ((client
->fd
= accept(server
->fd
, (void*)&client
->addr
, &clen
)) == -1)*-1;
39 int server_setup(struct server
*server
, const char* listenip
, unsigned short port
) {
40 struct addrinfo
*ainfo
= 0;
41 if(resolve(listenip
, port
, &ainfo
)) return -1;
44 for(p
= ainfo
; p
; p
= p
->ai_next
) {
45 if((listenfd
= socket(p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) < 0)
48 setsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(int));
49 if(bind(listenfd
, p
->ai_addr
, p
->ai_addrlen
) < 0) {
57 if(listenfd
< 0) return -2;
58 if(listen(listenfd
, SOMAXCONN
) < 0) {
62 server
->fd
= listenfd
;