欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UDP 局域网广播包 Linux/Mac 服务端 客户端 Windows客户端 测试代码

程序员文章站 2022-06-06 08:43:20
...

昨晚为了整理了局域网广播测试代码,自己懒得写,网上copy整理下,用Linux/Mac做服务端,WIN10客户端。

目的主要测试下WIN10下广播包的收发。有兴趣可以参考下。在局域网多台电脑上测试下广播包的收发.

demo代码来源于网络,稍做修改,这里做了个全平台整理,方便测试。如有不妥,请联系本人。

 

WIN10用VC2017创建一个CONSOLE工程。编译运行即可,CONSOLE中监听CTR-C事件,否则无法退出。编译运行即可

winclient.cpp


#include <iostream>

#include <WinSock2.h>  
#include <windows.h> 
#include <stdio.h> 

#pragma comment(lib, "WS2_32.lib") 

BOOL mbCloseConsole = false;

BOOL CtrlHandler(DWORD fdwCtrlType)
{
	switch (fdwCtrlType)
	{
		// Handle the CTRL-C signal. 
	case CTRL_C_EVENT:
		printf("Ctrl-C event/n/n");
		mbCloseConsole = true;
		return(TRUE);

	case CTRL_CLOSE_EVENT:
		printf("Ctrl-Close event/n/n");
		mbCloseConsole = true;
		return(TRUE);

	default:
		return FALSE;
	}
	return TRUE;
}


int main(int argc, char* argv[])
{
	WORD wVersionRequested = MAKEWORD(2, 2);
	WSADATA wsaData;
	mbCloseConsole = false;
	if (0 != WSAStartup(wVersionRequested, &wsaData))
	{
		printf("WSAStartup failed with error: %d/n", GetLastError());
		return EXIT_FAILURE;
	}
	if (2 != HIBYTE(wsaData.wVersion) || 2 != LOBYTE(wsaData.wVersion))
	{
		printf("Socket version not supported./n");
		WSACleanup();
		return EXIT_FAILURE;
	}
	SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (INVALID_SOCKET == sock)
	{
		printf("socket failed with error: %d/n", WSAGetLastError());
		WSACleanup();
		return EXIT_FAILURE;
	}
	SOCKADDR_IN addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);
	addr.sin_port = htons(5001);
	BOOL bBoardcast = TRUE;
	if (SOCKET_ERROR == setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&bBoardcast, sizeof(bBoardcast)))
	{
		printf("setsockopt failed with error code: %d/n", WSAGetLastError());
		if (INVALID_SOCKET != sock)
		{
			closesocket(sock);
			sock = INVALID_SOCKET;
		}
		WSACleanup();
	}
	printf("Server start, start to boardcast .../n");
	char buf[] = { "Hello, this is boardcast!" };
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
	while (!mbCloseConsole)
	{
		if (SOCKET_ERROR == sendto(sock, buf, sizeof(buf), 0, (LPSOCKADDR)&addr, sizeof(addr)))
		{
			printf("sendto failed with error: %d/n", WSAGetLastError());
			continue;
		}
	}
	WSACleanup();
	return 0;
}

 

LINUX MAC下做服务端

server.cpp

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
 
using namespace std;
 
int main()
{
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<<"socket error"<<endl;	
		return false;
	}   
	
	const int opt = 1;
	//设置该套接字为广播类型,
	int nb = 0;
	nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
	if(nb == -1)
	{
		cout<<"set socket error..."<<endl;
		return false;
	}
 	//指定Server IP  和  发送给Client的端口
	struct sockaddr_in addrto;
	bzero(&addrto, sizeof(struct sockaddr_in));
	addrto.sin_family=AF_INET;
	addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST);
	addrto.sin_port=htons(5001);
	int nlen=sizeof(addrto);
 	cout<<"send broadcast... "<<endl;
	while(1)
	{
		sleep(1);
		//从广播地址发送消息
		char smsg[] = {"abcdef"};
		int ret=sendto(sock, smsg, strlen(smsg), 0, (sockaddr*)&addrto, nlen);
		if(ret<0)
		{
			cout<<"send error...."<<ret<<endl;
		}
		else
		{		
			cout<<"send broadcast ok... "<<endl;	
		}
		cout<<"send broadcast : "<<ret<<endl;
		
	}
	return 0;
}

命令行运行 g++  server.cpp -o server  然后执行 ./server即可

 

LINUX MAC下客户端

client.cpp

 

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
 
using namespace std;
 
int main()
{
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<<"socket error"<<endl;	
		return false;
	}   
	
	// 广播地址
	struct sockaddr_in from;
	bzero(&from, sizeof(struct sockaddr_in));
	from.sin_family = AF_INET;
	from.sin_addr.s_addr = htonl(INADDR_ANY);
	from.sin_port = htons(5001);


	
	if(bind(sock,(struct sockaddr *)&(from), sizeof(struct sockaddr_in)) == -1) 
	{   
		cout<<"bind error..."<<endl;
		return false;
	}
 
	int len = sizeof(sockaddr_in);
	char smsg[100] = {0};
 
	while(1)
	{
		//从广播地址接受消息
		int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);
		if(ret<=0)
		{
			cout<<"read error...."<<sock<<endl;
		}
		else
		{		
			printf("%s\t", smsg);	
		}
		cout<<"RECV::::"<<ret<<endl;
		sleep(1);
	}
	return 0;
}

命令行运行 g++  client.cpp -o client  然后执行 ./client即可