c++ - recvfrom 非阻塞返回 C++ 中的 BAD ADDRESS 错误
问题描述
我在尝试收听而不是发送时收到“BAD ADDRESS”错误。发送与 sendto() 完美配合。
这是创建要侦听的套接字的函数。IP 和端口是本地的(这是为了在同一个本地网络中执行,实际上是在使用 linux 虚拟机和 windows 机器的同一台 pc 中)。
在 getaddrinfo(NULL, port, &hints, &addrInfoResults); 中使用 NULL 似乎要走的路:不知道为什么使用发件人的本地 IP(例如 192.168.1.50)不起作用。但发送工作。
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);
连接时,任何呼叫均未收到错误消息。套接字已创建。接听电话是这个:
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;
....
为什么我收到 BAD Address 错误?我已阅读与此相关的所有帖子,但没有任何帮助。我总是收到-1。
到目前为止我所做的测试:
- 检查地址的大小。地址和长度是一样的。
- 我创建了两个小控制台程序,令人惊讶的是它可以工作。仅当我将 getaddrinfo 设置为 NULL 时才会收到数据,但设置 IP 不起作用。这令人困惑。没有什么不同。
解决方案
只是为了让大家知道这件事。如果您有 BAD ADDRESS,如 IBM 文档所述:
调用 recvfrom 时:缓冲区(指向 NULL)、地址(指向错误的位置,或者您没有传递对实际位置的引用而不是指针)或地址的大小(即你没有正确计算它)。
我的问题是我没有初始化缓冲区。
推荐阅读
- powershell - 函数内部的 Import-Module,并使其在所有脚本中可用
- reactjs - 如何更改 react-select 中所有元素(边框、文本和箭头)的悬停?
- graphql - 如何从 Apollo Server 实现中使用其他 GraphQL API?
- objective-c - 隐式转换失去整数精度:“NSInteger”(又名“long”)到“int”
- javascript - 如何在反应组件上导入 highlight.js?
- excel - 更改代码的VBA编译是否对循环中的错误结果负责?
- python - Tensorflow 对象检测 API 中的预测数量限制
- android - 用两根手指缩小/放大“活动”
- python - 动画 QGraphicsPixmapItem
- javascript - 如何在十六进制网格上用图像替换悬停文本