- memset (&hints, 0, sizeof (hints));
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags |= AI_CANONNAME;
- if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
- iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
- return NULL;
+
+ //prevent SIGPIPE
+ #ifndef WIN32
+ #if defined(SO_NOSIGPIPE)
+ opt = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&opt, sizeof(opt));
+ #else
+ signal(SIGPIPE, SIG_IGN);
+ #endif
+ #endif
+ //make sockfd unblocking
+ #if defined(F_GETFL)
+ opt = fcntl(sockfd, F_GETFL);
+ fcntl(sockfd, F_SETFL, opt|O_NONBLOCK);
+ opt = fcntl(sockfd, F_GETFD);
+ fcntl(sockfd, F_SETFD, opt|FD_CLOEXEC);
+ #endif
+
+ if(iostartup->listening) {
+ opt = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&opt, sizeof(opt));
+ } else {
+ if((iostartup->iptype & IODNS_RECORD_AAAA)) {
+ struct sockaddr_in6 *ip6ptr = iostartup->use_srcaddr->address;
+ ip6ptr->sin6_family = addr_family;
+ ip6ptr->sin6_port = htons(iostartup->port);
+ } else {
+ struct sockaddr_in *ip4ptr = iostartup->use_srcaddr->address;
+ ip4ptr->sin_family = addr_family;
+ ip4ptr->sin_port = htons(iostartup->port);
+ }
+ }
+
+ // Bind Socket to IP
+ if(iostartup->listening || iostartup->use_srcaddr) {
+ if((iostartup->iptype & IODNS_RECORD_AAAA)) {
+ memset(&ip6, 0, sizeof(ip6));
+ if(iostartup->use_srcaddr) {
+ struct sockaddr_in6 *ip6ptr = iostartup->use_srcaddr->address;
+ ip6.sin6_addr = ip6ptr->sin6_addr;
+ } else
+ inet_pton(AF_INET6, "::1", &ip6.sin6_addr);
+ ip6.sin6_family = addr_family;
+ ip6.sin6_port = htons((iostartup->listening ? iostartup->port : 0));
+ opt = bind(sockfd, (struct sockaddr*)&ip6, sizeof(ip6));
+ } else {
+ memset(&ip6, 0, sizeof(ip6));
+ if(iostartup->use_srcaddr) {
+ struct sockaddr_in4 *ip4ptr = iostartup->use_srcaddr->address;
+ ip6.sin6_addr = ip4ptr->sin_addr;
+ } else
+ ip4.sin_addr = INADDR_ANY;
+ ip4.sin_family = addr_family;
+ ip4.sin_port = htons((iostartup->listening ? iostartup->port : 0));
+ opt = bind(sockfd, (struct sockaddr*)&ip4, sizeof(ip4));
+ }
+ if(!opt) {
+ callback_event.type = IOEVENT_BIND_ERROR;
+ goto iohandler_process_iostartup_fail;
+ }