Browse Source Download (without any required ccan dependencies)

Module:

net

Summary:

simple IPv4/IPv6 socket library

Author:

Rusty Russell <rusty@rustcorp.com.au>

Dependencies:

Description:

This code makes it simple to support IPv4 and IPv6 without speed penalty in clients by using non-blocking simultaneous connect, and using a convenience function to create both IPv4 and IPv6 sockets for servers.

Example:

#include <ccan/net/net.h>
#include <netinet/in.h>
#include <stdio.h>
#include <err.h>

int main(int argc, char *argv[])
{
        struct addrinfo *addr;
        const char *dest, *port;
        int fd;
        union {
                struct sockaddr s;
                struct sockaddr_in v4;
                struct sockaddr_in6 v6;
        } u;
        socklen_t slen = sizeof(u);

        if (argc == 2) {
                dest = argv[1];
                port = "http";
        } else if (argc == 3) {
                dest = argv[1];
                port = argv[2];
        } else
                errx(1, "Usage: test-net <target> [<port>]");

        addr = net_client_lookup(dest, port, AF_UNSPEC, SOCK_STREAM);
        if (!addr)
                err(1, "Failed to look up %s", dest);

        fd = net_connect(addr);
        if (fd < 0)
                err(1, "Failed to connect to %s", dest);
        freeaddrinfo(addr);

        if (getsockname(fd, &u.s, &slen) == 0)
                printf("Connected via %s\n",
                       u.s.sa_family == AF_INET6 ? "IPv6"
                       : u.s.sa_family == AF_INET ? "IPv4"
                       : "UNKNOWN??");
        else
                err(1, "Failed to get socket type for connection");
        return 0;
}

License:

MIT