我编写了一个程序来发送数据并通过UDP并行监听数据。为此,我创建了几个函数:
int initiate_TXRX_variables(void)
{
struct hostent * hp;
hp = gethostbyname("localhost");
if(hp == NULL)
return INVALID_SOCKET;
memset(&sa_udp_in, 0, sizeof(sa_udp_in));
memset(&sa_tcp_in, 0, sizeof(sa_tcp_in));
memset(&sa_udp_out, 0, sizeof(sa_udp_out));
memset(&sa_tcp_in, 0, sizeof(sa_tcp_in));
memcpy((char *)&sa_udp_in.sin_addr, hp->h_addr, hp->h_length);
memcpy((char *)&sa_tcp_in.sin_addr, hp->h_addr, hp->h_length);
memcpy((char *)&sa_udp_out.sin_addr, hp->h_addr, hp->h_length);
memcpy((char *)&sa_tcp_out.sin_addr, hp->h_addr, hp->h_length);
sa_udp_in.sin_family = hp->h_addrtype;
sa_tcp_in.sin_family = hp->h_addrtype;
sa_udp_out.sin_family = hp->h_addrtype;
sa_tcp_out.sin_family = hp->h_addrtype;
sa_udp_in.sin_port = htons((u_short)PORTNUM_UDP_IN);
sa_tcp_in.sin_port = htons((u_short)PORTNUM_TCP_IN);
sa_udp_out.sin_port = htons((u_short)PORTNUM_UDP_OUT);
sa_tcp_out.sin_port = htons((u_short)PORTNUM_TCP_OUT);
return 1;
}
int ultra_spam_network_udp(void)
{
struct hostent *hp, *local;
hp = gethostbyname("192.168.70.0");
hp = gethostbyname("255.255.255.255");
local = gethostbyname("localhost");
memcpy((char *)&sa_udp_out.sin_addr,hp->h_addr, hp->h_length);
//set_ip_udp_out(htonl(ntohl(sa_udp_out.sin_addr.s_addr) - 1));
InetPton(AF_INET, "192.168.30.0", &(sa_udp_out.sin_addr));
char str[] = "Hello";
char ipstr[256];
for(int i = 0; i < 256; i++)
{
std::cout << "Local: " << retLocalIP() << " and current IP: " << /*inet_ntoa(sa_udp_out.sin_addr)*/InetNtop(AF_INET, &(sa_udp_out.sin_addr), ipstr, 256) << " with counter: " << i << '\n';
sendto(UDP_OUT, str, sizeof(str), 0, (struct sockaddr*)&sa_udp_out, sizeof(sa_udp_out));
sa_udp_out.sin_addr.s_addr = htonl(ntohl(sa_udp_out.sin_addr.s_addr)+1);
};
//sendto(UDP_OUT, str, sizeof(str), 0, (struct sockaddr*)&sa_udp_out, sizeof(sa_udp_out));
return 0;
}
int/*char **/ listen_udp_debug(void)
{
struct sockaddr_in from;
int fromlen = sizeof(from);
char inStr[100];
char * ptr = &inStr[0];
int ret = recvfrom(UDP_IN, inStr, sizeof(inStr), 0, (struct sockaddr *)&from, &fromlen);
std::cout << "From listen_udp_debug: " << ret << " with error number " << WSAGetLastError() << '\n';
//return ptr;
return 0;
}
我通过
调用这些函数 initiate_TXRX_variables();
boost::thread thread_1 = boost::thread(ultra_spam_network_udp);
listen_udp_debug();
IN和OUT的PORTNUMS当然不同。我的问题是,现在我在调用listen_udp_debug()
时收到错误10022。为什么我会收到此错误,我该怎么做才能绕过这个错误呢?
非常感谢你!
答案 0 :(得分:0)
发现我的问题,我必须在我的udp_receive函数中使用bind(),否则它将无效。