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

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

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

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

 

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

winclient.cpp


#include 

#include   
#include  
#include  

#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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
 
using namespace std;
 
int main()
{
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<<"socket error"<

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

 

LINUX MAC下客户端

client.cpp

 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
 
using namespace std;
 
int main()
{
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<<"socket error"<

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

你可能感兴趣的:(网络通讯)