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 server_bindtoip(const struct server
*server
, int fd
) {
18 if(server
->bindaddr
.v4
.sin_family
!= AF_UNSPEC
)
19 return bind(fd
, (struct sockaddr
*) &server
->bindaddr
, server
->bindaddrsz
);
23 int server_waitclient(struct server
*server
, struct client
* client
) {
24 socklen_t clen
= sizeof client
->addr
;
25 return ((client
->fd
= accept(server
->fd
, (void*)&client
->addr
, &clen
)) == -1)*-1;
28 int server_setup(struct server
*server
, const char* listenip
, unsigned short port
) {
29 struct addrinfo
*ainfo
= 0;
30 if(resolve(listenip
, port
, &ainfo
)) return -1;
33 for(p
= ainfo
; p
; p
= p
->ai_next
) {
34 if((listenfd
= socket(p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) < 0)
37 setsockopt(listenfd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(int));
38 if(bind(listenfd
, p
->ai_addr
, p
->ai_addrlen
) < 0) {
45 if(listenfd
< 0) return -2;
47 if(listen(listenfd
, SOMAXCONN
) < 0) {
51 server
->fd
= listenfd
;
52 if(!resolve(listenip
, 0, &ainfo
)) {
53 server
->bindaddrsz
= ainfo
->ai_addrlen
;
54 memcpy(&server
->bindaddr
, ainfo
->ai_addr
, ainfo
->ai_addrlen
);
56 } else server
->bindaddr
.v4
.sin_family
= AF_UNSPEC
;