我正在尝试从UDP广播中获取数据,但没有recvfrom
函数的响应。连接,绑定,一切都很好。
广播会有问题吗?
无论如何我可以检查确切的错误吗?
#include <iostream>
using namespace std;
//#include <ServerSocket.h>
#include <cstring>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
enter code here
int status;
int socketfd;
int enableMulticast = 1; // Argument for set socket
struct addrinfo host_info; // The struct that getaddrinfo() fills up with data.
struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's.
struct sockaddr_in socketAddr;
unsigned char incomming_data_buffer[IN_LEN];
socklen_t socklen;
#ifndef IN_LEN
#define IN_LEN 4096
#endif
memset(&host_info, 0, sizeof host_info);
memset(&socketAddr, 0, sizeof(struct sockaddr_in));
cout << "Setting up the structs..." << endl;
host_info.ai_family = AF_UNSPEC; // IP version not specified. Can be both.
host_info.ai_socktype = SOCK_DGRAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
host_info.ai_protocol = IPPROTO_UDP; // The protocol type for UDP. If left as zero, it will return all types
status = getaddrinfo("UDP IP Address","Port", &host_info, &host_info_list);
socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
host_info_list->ai_protocol);
if (socketfd == -1) cout << "socket error " ;
else cout << "socket created successfully " ;
status = setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &enableMulticast, sizeof(enableMulticast));
socketAddr.sin_family = AF_INET;
socketAddr.sin_port = htons(INT_PORT);
socketAddr.sin_addr.s_addr = htonl(INADDR_ANY);
status = bind(socketfd, (struct sockaddr *)&socketAddr, sizeof(struct sockaddr_in));
status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (status < 0) cout << "connect error" <<endl ;
cout << "Waiting to receive data..." << endl;
socklen = sizeof(struct socketAddr);
while(1){
status = recvfrom(socketfd, incomming_data_buffer, IN_LEN, 0, (struct sockaddr *)&socketAddr, &socklen);
if(status >= 0) {
cout << "data received" ;
freeaddrinfo(host_info_list);
close(socketfd);
exit(0);
}
}
}
答案 0 :(得分:1)
if(status = 0)
这永远不会成真。 (1)它是status == 0
的拼写错误; (2)它应该是status >= 0
,即status
是收到的数据报的长度。