socket_t client_socket (char const * host, char const * port) { socket_t sock=INVALID_SOCKET; struct addrinfo * info=make_addrinfo(host, port); if (info) { char hostname[NI_MAXHOST]; char portname[NI_MAXSERV]; if (!setnameinfo(info->ai_addr, info->ai_addrlen, hostname, portname)) goto END; NANOLOG("[%s:%s]\n", hostname, portname); sock=socket(info->ai_family, info->ai_socktype, info->ai_protocol); if (sock==INVALID_SOCKET) { NANOLOG("socket failed <%d>\n", nanonet_error()); goto END; } if (connect(sock, info->ai_addr, info->ai_addrlen)==INVALID_SOCKET) { NANOLOG("connect failed <%d>\n", nanonet_error()); close_socket_t(sock); sock=INVALID_SOCKET; goto END; } } else NANOLOG("make_addrinfo failed <%d>\n", nanonet_error()); END: freeaddrinfo(info); return sock; }
/* * Save this address on the server, if not already there. */ static void save_addr(ad_disc_cds_t *cds, sa_family_t af, uchar_t *addr, size_t alen) { struct addrinfo *ai, *new_ai, *last_ai; new_ai = make_addrinfo(af, addr, alen); if (new_ai == NULL) return; last_ai = NULL; for (ai = cds->cds_ai; ai != NULL; ai = ai->ai_next) { last_ai = ai; if (new_ai->ai_family == ai->ai_family && new_ai->ai_addrlen == ai->ai_addrlen && 0 == memcmp(new_ai->ai_addr, ai->ai_addr, ai->ai_addrlen)) { /* it's already there */ freeaddrinfo(new_ai); return; } } /* Not found. Append. */ if (last_ai != NULL) { last_ai->ai_next = new_ai; } else { cds->cds_ai = new_ai; } }
socket_t server_socket (char const * host, char const * port) { socket_t sock=INVALID_SOCKET; struct addrinfo * info=make_addrinfo(host, port); if (info) { char hostname[NI_MAXHOST]; char portname[NI_MAXSERV]; if (!setnameinfo(info->ai_addr, info->ai_addrlen, hostname, portname)) goto END; NANOLOG("server_socket [%s:%s]\n", hostname, portname); sock=socket(info->ai_family, info->ai_socktype, info->ai_protocol); if (sock==INVALID_SOCKET) { NANOLOG("socket failed <%d>\n", nanonet_error()); goto END; } { char const enable = '1'; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int))==SOCKET_ERROR) { NANOLOG("setsockopt <%s>\n", nanonet_error_tostring(nanonet_error())); close_socket_t(sock); sock=INVALID_SOCKET; goto END; } } if (bind(sock, info->ai_addr, info->ai_addrlen)) { NANOLOG("bind failed <%d>\n", nanonet_error()); close_socket_t(sock); sock=INVALID_SOCKET; goto END; } if (listen(sock, SOMAXCONN)) { NANOLOG("listen failed <%d>\n", nanonet_error()); close_socket_t(sock); sock=INVALID_SOCKET; goto END; } } else NANOLOG("make_addrinfo failed <%d>\n", nanonet_error()); END: freeaddrinfo(info); return sock; }