gpt4 book ai didi

c++ - 尝试通过 udp 套接字广播

转载 作者:行者123 更新时间:2023-11-30 02:54:35 25 4
gpt4 key购买 nike

我的广播服务器遇到了问题。基本上,我希望它从我启动它的那一刻起就连续发送广播。出于某种原因,它不会启动,直到它从某个地方接收到连接。我一定是搞砸了什么,但我不知道是什么。

这是我的代码:

WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET sock;
sock = socket(AF_INET, SOCK_DGRAM, 0);
char broadcast = 'a';

if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0)
{
perror("broadcast options");
closesocket(sock);
return 1;
}
struct sockaddr_in Recv_addr;
struct sockaddr_in Sender_addr;
int len = sizeof(struct sockaddr_in);
char recvBuff[50];
int recvBuffLen = 50;
//char sendMsg[] = "broadcast message from salam rofl";

Recv_addr.sin_family = AF_INET;
Recv_addr.sin_port = htons(PORT);
Recv_addr.sin_addr.s_addr = INADDR_ANY;

if(bind(sock, (sockaddr*)&Recv_addr, sizeof(Recv_addr)) < 0)
{
perror("bind");
_getch;
closesocket(sock);
return 1;
}

//recvfrom(sock, recvBuff, recvBuffLen, 0, (sockaddr *)&Sender_addr, &len);
//cout << "\nreceived message: " << recvBuff;

while(1)
{
Sleep(3000);


//_getch();

getTime();
if(sendto(sock, currentTime, strlen(currentTime)+1, 0, (sockaddr *)&Sender_addr, sizeof(Sender_addr)) < 0)
{
perror("borhot send: ");
_getch();
closesocket(sock);
return 0;
}
else cout << "message sent successfully";
}

_getch;
closesocket(sock);
WSACleanup();
return 0;

基本上,如果我删除 recvfrom,它会给我一个发送错误(“无错误”),这让我很困惑。另外,如果我用客户端发送一些东西,它会开始广播,但如果我连接另一个客户端,只有第一个客户端正在接收广播。

提前致谢。我怀疑这是否重要,但我正在尝试广播当前时间。

最佳答案

您没有初始化 Sender_Addr,所以您没有告诉 sendto() 实际广播到哪里。

试试这个:

WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);

SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET)
{
perror("socket creation");
_getch;
return 1;
}

BOOL enabled = TRUE;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&enabled, sizeof(BOOL)) < 0)
{
perror("broadcast options");
_getch;
closesocket(sock);
return 1;
}

struct sockaddr_in Sender_addr;
Sender_addr.sin_family = AF_INET;
Sender_addr.sin_port = htons(BROADCAST_PORT);
Sender_addr.sin_addr.s_addr = inet_addr("Broadcast IP Here");

struct sockaddr_in Recv_addr;
Recv_addr.sin_family = AF_INET;
Recv_addr.sin_port = htons(PORT);
Recv_addr.sin_addr.s_addr = INADDR_ANY;

if (bind(sock, (sockaddr*)&Recv_addr, sizeof(Recv_addr)) < 0)
{
perror("bind");
_getch;
closesocket(sock);
return 1;
}

while(1)
{
Sleep(3000);

getTime();
if (sendto(sock, currentTime, strlen(currentTime)+1, 0, (sockaddr *)&Sender_addr, sizeof(Sender_addr)) < 0)
{
perror("borhot send: ");
_getch();
closesocket(sock);
return 0;
}

cout << "message sent successfully";
}

_getch;
closesocket(sock);

WSACleanup();
return 0;

关于c++ - 尝试通过 udp 套接字广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16973543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com