服务端
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
//设置套接字可以发送广播消息权限
bool optval = true;
setsockopt(serverSocket, SOL_SOCKET, SO_BROADCAST, (char*)&optval, sizeof(optval));
//SOCKADDR_IN serverSockAddr_in = { 0 };
//serverSockAddr_in.sin_family = AF_INET;
//serverSockAddr_in.sin_addr.S_un.S_addr = INADDR_ANY;
//serverSockAddr_in.sin_port = htons(6666);
//setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval));
//bind(serverSocket, (SOCKADDR*)&serverSockAddr_in, sizeof(serverSockAddr_in)); //不需要接收消息就不需要绑定了
//要发送的广播地址
SOCKADDR_IN broadcastSockAddr_in = { 0 };
broadcastSockAddr_in.sin_family = AF_INET;
broadcastSockAddr_in.sin_addr.S_un.S_addr = INADDR_BROADCAST; // inet_addr("172.16.20.255"); 本地广播地址/直接广播地址
broadcastSockAddr_in.sin_port = htons(6666);
while (true)
{
cout << "输入内容:";
char sendStr[100] = { 0 };
cin >> sendStr;
sendto(serverSocket, sendStr, sizeof(sendStr) - 1, 0, (SOCKADDR*)&broadcastSockAddr_in, sizeof(broadcastSockAddr_in));
//也可以自己发自己收(广播程序正常为服务端只负责发,客户端只负责收)
//char recvStr[100] = { 0 };
//recvfrom(serverSocket, recvStr, sizeof(recvStr)-1, 0,0,0);
//cout << "收到消息:" << recvStr << endl;
}
return 0;
}
客户端
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsaData = { 0 };
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET clientSocket = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN clientSockAddr_in = { 0 };
clientSockAddr_in.sin_family = AF_INET;
clientSockAddr_in.sin_addr.S_un.S_addr = INADDR_ANY;
clientSockAddr_in.sin_port = htons(6666);
bool optval = true;
setsockopt(clientSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)); //设置端口重用(非必要)
int bindRet = bind(clientSocket, (SOCKADDR*)&clientSockAddr_in, sizeof(clientSockAddr_in)); //显式绑定套接字用于消息
if (bindRet == SOCKET_ERROR)
{
cout << "绑定套接字失败\n";
closesocket(clientSocket);
WSACleanup();
system("pause");
return 0;
}
while (true)
{
char recvStr[100] = { 0 };
SOCKADDR_IN fromSockAddr_in = { 0 };
int len = sizeof(fromSockAddr_in);
recvfrom(clientSocket, recvStr, sizeof(recvStr) - 1, 0, (SOCKADDR*)&fromSockAddr_in, &len);
std::cout << "(" << inet_ntoa(fromSockAddr_in.sin_addr) << ":" << ntohs(fromSockAddr_in.sin_port) << "):" << recvStr << std::endl;
}
return 0;
}
|