mute warning about shadow declaration of bind_addr
[rofl0r-microsocks.git] / server.c
blob9f0ab9a9d37f0abc91b87e7a58666e1f4e62ea10
1 #include "server.h"
2 #include <stdio.h>
3 #include <string.h>
4 #include <unistd.h>
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,
12 char port_buf[8];
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;
19 int ret;
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);
23 freeaddrinfo(ainfo);
24 return 0;
27 int bindtoip(int fd, union sockaddr_union *bindaddr) {
28 socklen_t sz = SOCKADDR_UNION_LENGTH(bindaddr);
29 if(sz)
30 return bind(fd, (struct sockaddr*) bindaddr, sz);
31 return 0;
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;
42 struct addrinfo* p;
43 int listenfd = -1;
44 for(p = ainfo; p; p = p->ai_next) {
45 if((listenfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
46 continue;
47 int yes = 1;
48 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
49 if(bind(listenfd, p->ai_addr, p->ai_addrlen) < 0) {
50 close(listenfd);
51 listenfd = -1;
52 continue;
54 break;
56 freeaddrinfo(ainfo);
57 if(listenfd < 0) return -2;
58 if(listen(listenfd, SOMAXCONN) < 0) {
59 close(listenfd);
60 return -3;
62 server->fd = listenfd;
63 return 0;