OSDN Git Service

I was library can be compiled 20140223
[zither/ds-zither.git] / libms / socket_bind46.c
1
2 #include<sys/types.h>
3 #include<sys/socket.h>
4 #include<netinet/in.h>
5 #include<netdb.h>
6 #include<stdio.h>
7 #include<errno.h>
8 #include<unistd.h>
9 #include<string.h>
10 #include<stdlib.h>
11 #include<arpa/inet.h>
12
13
14 // proto type
15 // int socket_bind46(struct addrinfo * hints, char * addr, char * port, int * ls, int maxsock);
16
17 int socket_bind46(struct addrinfo * hints, char * addr, char * port, int * ls, int maxsock)
18 {
19 static struct addrinfo * res;
20 static struct addrinfo * res0;
21
22 int error;
23 int smax;
24 int sockmax;
25 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
26
27 #ifdef IPV6_V6ONLY
28 const int on = 1;
29 #endif
30
31
32 error = getaddrinfo(addr, port, hints, &res0);
33 if(error){
34    fprintf(stderr,"%s : %s: %s\n", addr, port, gai_strerror(error));
35    return -1;
36    }
37
38 smax = 0;
39 sockmax = -1;
40 for(res = res0; res && smax < maxsock; res = res->ai_next){
41    ls[smax] = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
42    if(ls[smax] < 0){
43       continue;
44       }
45    if(ls[smax] >= FD_SETSIZE){
46       close(ls[smax]);
47       ls[smax] = -1;
48       continue;
49       }
50 #ifdef IPV6_V6ONLY
51    if(res->ai_family == AF_INET6 && setsockopt(ls[smax], IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0){
52       perror("setsockopt");
53       ls[smax] = -1;
54       continue;
55       }
56 #endif
57    if(bind(ls[smax], res->ai_addr, res->ai_addrlen) < 0){
58       close(ls[smax]);
59       ls[smax] = -1;
60       continue;
61       }
62    if(listen(ls[smax], 5) < 0){
63       close(ls[smax]);
64       ls[smax] = -1;
65       continue;
66       }
67    error = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
68    if(error){
69       fprintf(stderr,"test: %s\n", gai_strerror(error));
70       return -1;
71       }
72    fprintf(stderr,"listen to %s %s %d\n", hbuf, sbuf, ls[smax]);
73    if(ls[smax] > sockmax){
74       sockmax = ls[smax];
75       smax++;
76       }
77    } /* */
78
79 return smax;
80 }
81
82
83
84