Make QTcpServer only for IPv4 connectivity

I am using an FTP server and it does not support IPv6 yet (IPv6 connections cannot use PORT and PASV, they must instead use EPRT and EPSV to specify data connections).

So I only need to accept IPv4 connections from my QTcpServer. Right now I am starting to listen to this code:

server->listen(QHostAddress::Any, port);

      

QHostAddress :: Any must be any IP, but Filezilla still manages to connect using IPv6 when I specify localhost instead of 127.0.0.1. I thought QHostAddress :: Any would only mean inbound IPv4 connections, but that's clearly not the case.

So how do I disable IPv6 connections?

+3


source to share


1 answer


In Qt4, it QHostAddress::Any

is only used for listening for IPv4 only, but with Qt5 it now listens on all available interfaces.

If you want to compile both Qt4 and Qt5, your code should look like this:

#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    server->listen(QHostAddress::AnyIPv4, port);
#else
    server->listen(QHostAddress::Any, port);
#endif

      

As the Qt5 link says:

QHostAddress :: Any Double stack any address. The socket associated with this address will listen on both IPv4 and IPv6 interfaces.

Based on QTcpServer, you should use



QHostAddress::AnyIPv4

      

QHostAddress :: AnyIPv4 Any IPv4 address. Equivalent to QHostAddress ("0.0.0.0"). The socket associated with this address will only listen on IPv4 interfaces.


Side note: what it does under the hood is creating the correct version of the socket i.e. AF_INET

or AF_INET6

:

int ipv4sockfd = socket( AF_INET, SOCK_STREAM, 0);

int ipv6sockfd = socket( AF_INET6, SOCK_STREAM, 0);

      

+8


source







All Articles