net: fix latent bug in _info example.
authorRusty Russell <rusty@rustcorp.com.au>
Sat, 29 Jan 2011 07:42:20 +0000 (18:12 +1030)
committerRusty Russell <rusty@rustcorp.com.au>
Sat, 29 Jan 2011 07:42:20 +0000 (18:12 +1030)
Ben Hutchings points out that struct sockaddr isn't large enough to hold
a struct sockaddr_in6.  Our example works because we only access the family
field, but anyone extending it might be surprised; use a union instead.

ccan/net/_info

index 0b38c440061fd77776091e8813c26e10f14c4937..845458c0eb0e2e4e5b09a161ccf54e1ffdab2bab 100644 (file)
@@ -14,6 +14,7 @@
  *     #include <ccan/net/net.h>
  *     #include <sys/types.h>
  *     #include <sys/socket.h>
+ *     #include <netinet/in.h>
  *     #include <stdio.h>
  *     #include <err.h>
  *
  *             struct addrinfo *addr;
  *             const char *dest, *port;
  *             int fd;
- *             struct sockaddr saddr;
- *             socklen_t slen = sizeof(saddr);
+ *             union {
+ *                     struct sockaddr s;
+ *                     struct sockaddr_in v4;
+ *                     struct sockaddr_in6 v6;
+ *             } u;
+ *             socklen_t slen = sizeof(u);
  *     
  *             if (argc == 2) {
  *                     dest = argv[1];
  *             if (fd < 0)
  *                     err(1, "Failed to connect to %s", dest);
  *     
- *             if (getsockname(fd, &saddr, &slen) == 0)
+ *             if (getsockname(fd, &u.s, &slen) == 0)
  *                     printf("Connected via %s\n",
- *                            saddr.sa_family == AF_INET6 ? "IPv6"
- *                            : saddr.sa_family == AF_INET ? "IPv4"
+ *                            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");