| 2571 | |
| 2572 | template <typename BindOrConnect> |
| 2573 | socket_t create_socket(const std::string &host, const std::string &ip, int port, |
| 2574 | int address_family, int socket_flags, bool tcp_nodelay, |
| 2575 | SocketOptions socket_options, |
| 2576 | BindOrConnect bind_or_connect) { |
| 2577 | // Get address info |
| 2578 | const char *node = nullptr; |
| 2579 | struct addrinfo hints; |
| 2580 | struct addrinfo *result; |
| 2581 | |
| 2582 | memset(&hints, 0, sizeof(struct addrinfo)); |
| 2583 | hints.ai_socktype = SOCK_STREAM; |
| 2584 | hints.ai_protocol = 0; |
| 2585 | |
| 2586 | if (!ip.empty()) { |
| 2587 | node = ip.c_str(); |
| 2588 | // Ask getaddrinfo to convert IP in c-string to address |
| 2589 | hints.ai_family = AF_UNSPEC; |
| 2590 | hints.ai_flags = AI_NUMERICHOST; |
| 2591 | } else { |
| 2592 | if (!host.empty()) { node = host.c_str(); } |
| 2593 | hints.ai_family = address_family; |
| 2594 | hints.ai_flags = socket_flags; |
| 2595 | } |
| 2596 | |
| 2597 | #ifndef _WIN32 |
| 2598 | if (hints.ai_family == AF_UNIX) { |
| 2599 | const auto addrlen = host.length(); |
| 2600 | if (addrlen > sizeof(sockaddr_un::sun_path)) return INVALID_SOCKET; |
| 2601 | |
| 2602 | auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); |
| 2603 | if (sock != INVALID_SOCKET) { |
| 2604 | sockaddr_un addr; |
| 2605 | addr.sun_family = AF_UNIX; |
| 2606 | std::copy(host.begin(), host.end(), addr.sun_path); |
| 2607 | |
| 2608 | hints.ai_addr = reinterpret_cast<sockaddr *>(&addr); |
| 2609 | hints.ai_addrlen = static_cast<socklen_t>( |
| 2610 | sizeof(addr) - sizeof(addr.sun_path) + addrlen); |
| 2611 | |
| 2612 | fcntl(sock, F_SETFD, FD_CLOEXEC); |
| 2613 | if (socket_options) { socket_options(sock); } |
| 2614 | |
| 2615 | if (!bind_or_connect(sock, hints)) { |
| 2616 | close_socket(sock); |
| 2617 | sock = INVALID_SOCKET; |
| 2618 | } |
| 2619 | } |
| 2620 | return sock; |
| 2621 | } |
| 2622 | #endif |
| 2623 | |
| 2624 | auto service = std::to_string(port); |
| 2625 | |
| 2626 | if (getaddrinfo(node, service.c_str(), &hints, &result)) { |
| 2627 | #if defined __linux__ && !defined __ANDROID__ |
| 2628 | res_init(); |
| 2629 | #endif |
| 2630 | return INVALID_SOCKET; |