Troubles with adding IPv6 support to a program

From: Chris Ross <cross+freebsd_at_distal.com>
Date: Sun, 12 Jun 2022 16:40:11 UTC
Tl;dr;
I don’t know why I’m getting an EINVAL from a call to bind for a second socket




20 years ago, I spent a lot of time adding IPv6 support to IPv4-only programs.
So I thought this (adding IPv6 support to simpleproxy[1]) would be an easy
project to pick up.  I’ve gotten most of the framework in, delayed only
slightly when I learned that FreeBSD is “different” in not routing IPv4
traffic to AF_INET6 sockets [2].

However, I’m getting an issue from one of my bind(2) calls that I’m not able
to figure out.  I was hoping someone else had a few minutes to take a quick
look and help me find out what I’m doing wrong.

A ~70 line relevant section of the source is at https://justpaste.it/6u3jd

The tl;dr; of this is that I:

* getaddrinfo(NULL, portIwant)
* for each address returned:
 * create a socket
 * setsockopt(SO_REUSEADDR)
 * bind
 * listen

The first address I get is IPv6 localhost, and that binds and listens, then
continues to the next address.  A new socket is created, setsockopt’d, but
bind for the second address (IPv4 localhost) fails with EINVAL.

As you can see in the code shared, I have lots of debugging logs in the code,
and it looks like everything is as it should be.  I’m probably just missing
Something simple, and am looking for another set of eyes.

Thanks all.  Contact me off list if you like, or on-list if it’s obvious
what I’ve done and it will help others.

              - Chris


[1] https://github.com/vzaliva/simpleproxy
[2] inet6(4), "Interaction between IPv4/v6 sockets"