Reputation: 2573
I'm getting a "BAD ADDRESS" error when trying to listen and not when sending. Sending works perfectly with sendto().
Here's the function that creates the socket to listen. IP and Port are local (this is intented to execute in the same local network, in fact, in the same pc using a linux virtual machine and a windows machine).
Using NULL in getaddrinfo(NULL, port, &hints, &addrInfoResults); seems like the way to go: no idea why using the local IP of the sender (192.168.1.50 for example) would not work. But sending works.
int socketDescriptor;
sockaddr socketAddress;
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; // Allow only IPv4
hints.ai_socktype = SOCK_DGRAM; // Datagram socket, type of packages used in UDP
hints.ai_protocol = IPPROTO_UDP; // UDP protocol
hints.ai_flags = AI_PASSIVE; // USE MY IP
// resolve dynamically IP adress by getaddrinfo()
struct addrinfo *addrInfoResults;
int resVal = getaddrinfo(ip, port, &hints, &addrInfoResults);
if (resVal != 0) {
// ERROR
return false;
}
struct addrinfo *addInf;
for(addInf = addrInfoResults;addInf != NULL; addInf = addInf->ai_next) {
if (addInf->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)addInf->ai_addr;
void *addr = &(ipv4->sin_addr);
// convert the IP to a string
char ipstr[16]; // IPv4 is 16
inet_ntop(addInf->ai_family, addr, ipstr, sizeof ipstr);
break;
}
}
// Create connection with socket
socketDescriptor = 0;
if ( (socketDescriptor = socket(addInf->ai_family, addInf->ai_socktype, addInf->ai_protocol)) == -1)
{
// ERROR...
return false;
}
// Try to bind to that address
if (bind(socketDescriptor, addInf->ai_addr, addInf->ai_addrlen) == -1)
{
// ERROR
return false;
}
socketAddress = *(addInf->ai_addr);
freeaddrinfo(addrInfoResults);
// Set socket non blocking
fcntl(socketDescriptor, F_SETFL, O_NONBLOCK);
When connecting, no error is received from any call. Socket is created. The call to receive is this one:
socklen_t addrSize = sizeof(socketAddress);
int numbytes = recvfrom(socketDescriptor,
buffer,
sizeof(bufferStruct),
0,
&socketAddress,
&addrSize);
if (numbytes < 0)
{
int errnoBackup = errno;
if (errnoBackup != EWOULDBLOCK && errnoBackup != EAGAIN)
{
_logFile << "ERROR" << std::endl;
....
Why am I getting a BAD Address error? I've read all posts related to this and none help. I'm always receiving a -1.
Tests I've done so far:
Upvotes: 0
Views: 501
Reputation: 2573
Just for everybody to know about this. In case you have BAD ADDRESS, as IBM documentation depicts:
When calling recvfrom: It is a problem with the buffer (pointing to NULL), the address (pointing to a wrong place or you are not passing the reference to the actual place and not a pointer), or the size of the address (that you didn't calculate it correctly).
My problem was that I didn't initialize the buffer.
Upvotes: 1