UDP广播

服务器端
#include<iostream>
#include<WinSock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")


int main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD( 2, 2 );
	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 )
	{
		return 0;
	}
	if ( LOBYTE( wsaData.wVersion ) != 2 ||HIBYTE( wsaData.wVersion ) != 2 )
	{
		WSACleanup( );
		return 0; 
	}
	//创建socket
	SOCKET socketSevere=socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP);
	if(INVALID_SOCKET==socketSevere)
	{
		cout<<"socket at error"<<endl;
		return 0;
	}
	sockaddr_in RecvAddr;
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(1234);
	RecvAddr.sin_addr.s_addr = inet_addr("192.168.1.255");
	//没有绑定服务器
	//将当前套接字设置为广播类型
	bool bOptval = TRUE;
	setsockopt(socketSevere,SOL_SOCKET,SO_BROADCAST,(const char *)bOptval,sizeof(bool));
	//send to
	char szbuf[1024]={0};
	while(1)
	{
		cin>>szbuf;
		sendto(socketSevere,szbuf,1024,0,(SOCKADDR*)&RecvAddr,sizeof(sockaddr));
	}
	closesocket(socketSevere);
	WSACleanup();
	system("pause");
	return 0;
}
客户端
#include<iostream>

#include<WinSock2.h>
using namespace std;


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

int main()
{
	//加载库
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD( 2, 2 );
	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 ) 
	{			                     
		return 0;
	}
	if ( LOBYTE( wsaData.wVersion ) != 2 ||HIBYTE( wsaData.wVersion ) != 2 ) 
	{
		WSACleanup( );
		return 0; 
	}
	//创建socket
	SOCKET socketlisten=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	if(INVALID_SOCKET==socketlisten)
	{
		cout<<"socket at error"<<endl;
		return 0;
	}
	sockaddr_in RecvAddr;
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(1234);
	RecvAddr.sin_addr.s_addr = inet_addr("192.168.1.121");
	if(SOCKET_ERROR==bind(socketlisten,(const sockaddr*)&RecvAddr,sizeof(sockaddr)))
	{
		cout<<"bind at error"<<endl;
	}
	char szbuf[1024]={0};
	int nLen=sizeof(sockaddr_in);
	while(1)
	{
		recvfrom(socketlisten,szbuf,1024,0,(SOCKADDR*)&RecvAddr,&nLen);
		cout<<szbuf<<endl;
	}
	closesocket(socketlisten);
	WSACleanup();
	system("pause");
	return 0;
}

你可能感兴趣的:(UDP广播)