首先 UDP 默认不能实现广播
要实现一个机子的广播,首先 应该明白2个函数
1.setsockopt 开启发送广播报文
2.getsockopt 确定广播选项是否关闭
setsockopt 的原型定义:
WINSOCK_API_LINKAGE int WSAAPI setsockopt( IN SOCKET s, IN int level, IN int optname, IN const char FAR * optval, IN int optlen )
开启报文代码
if (setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&bborad,oplen) == SOCKET_ERROR)
{
printf("setsockopt error!");
return 0;
}
作为server:
然后发送广播报文
sockaddr_in addr;
int nlen = sizeof(addr);
memset(&addr,0,nlen);
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.s_addr =INADDR_BROADCAST;
const char *msg = "hello! This is a test!";
int len = strlen(msg);
if (sendto(sock,msg,len,0,(struct sockaddr *)&addr,sizeof(addr)) == SOCKET_ERROR)
{
printf("send error !!");
return 0;
}
然后客户端:
接受报文:
2008年12月8日
# include <WinSock2.h>
# include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
#define WSVERS MAKEWORD(2,0)
//CInitSock initSock;
int main()
{
WSADATA wsadata;
if(WSAStartup(WSVERS,&wsadata))
{
printf("WSAStartup failed!\n");
return 0;
}
SOCKET sLiten = ::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sLiten == INVALID_SOCKET)
{
printf("WSACleanup failed with error %d\n",WSAGetLastError());
//printf(" Failed socket()");
return 0;
}
sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(9999);
local.sin_addr.s_addr =INADDR_ANY;
if(::bind(sLiten,(LPSOCKADDR)&local,sizeof(local)) == SOCKET_ERROR)
{
printf(" failed bind()");
return 0;
}
char buf[1024];
sockaddr_in addr;
int nlen = sizeof(addr);
while(1)
{
int recv = ::recvfrom(sLiten,buf,1024,0,(sockaddr *)&addr,&nlen);
if(recv )
{
buf[recv] = '\0';
printf("接收到数据 (%s): (%s)",::inet_ntoa(addr.sin_addr),buf);
}
}
::closesocket(sLiten);
return 0;
}