Commit 72744050 authored by Rusty Russell's avatar Rusty Russell

net: fix latent bug in _info example.

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.
parent 285338ec
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
* #include <ccan/net/net.h> * #include <ccan/net/net.h>
* #include <sys/types.h> * #include <sys/types.h>
* #include <sys/socket.h> * #include <sys/socket.h>
* #include <netinet/in.h>
* #include <stdio.h> * #include <stdio.h>
* #include <err.h> * #include <err.h>
* *
...@@ -22,8 +23,12 @@ ...@@ -22,8 +23,12 @@
* struct addrinfo *addr; * struct addrinfo *addr;
* const char *dest, *port; * const char *dest, *port;
* int fd; * int fd;
* struct sockaddr saddr; * union {
* socklen_t slen = sizeof(saddr); * struct sockaddr s;
* struct sockaddr_in v4;
* struct sockaddr_in6 v6;
* } u;
* socklen_t slen = sizeof(u);
* *
* if (argc == 2) { * if (argc == 2) {
* dest = argv[1]; * dest = argv[1];
...@@ -42,10 +47,10 @@ ...@@ -42,10 +47,10 @@
* if (fd < 0) * if (fd < 0)
* err(1, "Failed to connect to %s", dest); * 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", * printf("Connected via %s\n",
* saddr.sa_family == AF_INET6 ? "IPv6" * u.s.sa_family == AF_INET6 ? "IPv6"
* : saddr.sa_family == AF_INET ? "IPv4" * : u.s.sa_family == AF_INET ? "IPv4"
* : "UNKNOWN??"); * : "UNKNOWN??");
* else * else
* err(1, "Failed to get socket type for connection"); * err(1, "Failed to get socket type for connection");
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment