Qt - QUdpSocket bind failed constantly

2.3k views Asked by At

I have these 2 lines of code. I need a socket that just receives data

The first method is working, and I receive date (from the ip/port in the second method)

The second method is always returning false.

I don't understand the difference and can't find the problem.

Any one have any idea how to resolve this or what I'm doing wrong?

 udpSocket = new QUdpSocket(); 
bool result = udpSocket->bind(QHostAddress::Any, 7755);


QHostAddress address("the ip") 
udpSocket = new QUdpSocket(); 
bool result = udpSocket->bind(address , 7755);
1

There are 1 answers

0
Mohammad Kanan On

In first method, when you bind the socket bind(QHostAddress::Any, 7755) it will listen on all interfaces on your system; thus it will bind successfully knowing that at least one interface is up.

In the second method, when you set the IP Address with QHostAddress address("the ip") you need to make sure that an interface is up with that IP address at your system (use ipconfig on Win / ifconfig on Linux). Now the constructor will automatically detect from the string passed ("ip address") whether its IPv4 or IPv6. If you are not specifying a type, then you can construct the address as Any and bind your socket to it:

QString string("192.168.1.1");
QHostAddress address(QHostAddress::Any);
address.setAddress(string);
udpSocket = new QUdpSocket();
bool result = udpSocket->bind(address , 7755);