Fixes #1994 (closed) and #2211 (closed), plus a few additional improvements. These fixes are lightly-related, but when making a bunch of changes to the same file at once, it's easiest to use one merge request to keep things in order. See individual commit messages for details.
CC @pgriffis since he's the best reviewer for this code.
CC @mcrha and @Hi-Angel since my very quick attempt to disable IPv6 didn't seem to actually work, and it would be great if one of you could test this just to confirm the error message from #2211 (closed) really is fixed now.