ListenSocket: Fallback to ipv4

If we can't create a listener socket with the ipv6 protocol, try to
create one with the ipv4 protocol instead. This fixes the ListenSocket
on machines where ipv6 is not available or has been completely disabled.

This patch also exists ListenSocket::Listen() early if we fail to create
the socket.
This commit is contained in:
Leander Beernaert 2020-04-09 12:17:59 +02:00
parent 241f59b59f
commit 4201ebb28d

View File

@ -312,6 +312,16 @@ bool ListenSocket::Listen( int port, int backlog )
if( getaddrinfo( nullptr, portbuf, &hints, &res ) != 0 ) return false; if( getaddrinfo( nullptr, portbuf, &hints, &res ) != 0 ) return false;
m_sock = socket( res->ai_family, res->ai_socktype, res->ai_protocol ); m_sock = socket( res->ai_family, res->ai_socktype, res->ai_protocol );
if (m_sock == -1) {
// IPV6 protocol may not be available/is disabled. Try to create a socket
// with the IPV4 protocol
hints.ai_family = AF_INET;
if( getaddrinfo( nullptr, portbuf, &hints, &res ) != 0 ) return false;
}
m_sock = socket( res->ai_family, res->ai_socktype, res->ai_protocol );
if (m_sock == -1) {
return false;
}
#if defined _WIN32 || defined __CYGWIN__ #if defined _WIN32 || defined __CYGWIN__
unsigned long val = 0; unsigned long val = 0;
setsockopt( m_sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&val, sizeof( val ) ); setsockopt( m_sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&val, sizeof( val ) );