客户端:
SOCKET sSrv;
sockaddr_in addrto;
WSADATA wsdata;
BOOL bsocket;
//启动SOCKET库,版本为2.0
WORD wVer = MAKEWORD(2, 0);
if( 0 != WSAStartup(wVer,&wsdata) )
{
AfxMessageBox(L"Not Support Soket2.0");
return;
}
sSrv=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_OVERLAPPED);
bsocket=TRUE;
//然后赋值给地址,用来从网络上的广播地址接收消息;
addrto.sin_family=AF_INET;
addrto.sin_addr.s_addr=INADDR_BROADCAST;
addrto.sin_port=htons(nPort); // 与服务器端的相同
//设置该套接字为广播类型
BOOL bSetBroadcast=TRUE;
setsockopt(sSrv,SOL_SOCKET,SO_BROADCAST,(char FAR *)&bSetBroadcast,sizeof(bSetBroadcast));
char szMsg[]="Get IPAddr";
int nLen=sizeof(addrto);
if( SOCKET_ERROR==sendto(sSrv, szMsg, strlen(szMsg), 0, (sockaddr*)&addrto, nLen) )
AfxMessageBox(L"Send UDP Failed");
服务器端:
SOCKET sClient;
sockaddr_in clientAddr,bindAddr;
WSADATA wsdata;
//启动SOCKET库,版本为2.0
WORD wVer=MAKEWORD(2,0);
if( 0 != WSAStartup(wVer,&wsdata) )
{
AfxMessageBox(L"Not Support Socket2.0");
return;
}
//用UDP初始化套接字
sClient=socket(AF_INET,SOCK_DGRAM,0);
//设置该套接字为广播类型,
BOOL optval=TRUE;
bindAddr.sin_family=AF_INET;
bindAddr.sin_addr.s_addr=htonl(INADDR_ANY);
bindAddr.sin_port=htons(m_nPort);
setsockopt(sClient,SOL_SOCKET,SO_BROADCAST,(char FAR *)&optval,sizeof(optval));
bind(sClient,(sockaddr *)&bindAddr,sizeof(sockaddr_in));
char buf[256] = {0};
int fromlength=sizeof(SOCKADDR);
while(1)
{
int nRet = recvfrom(sClient,buf,256,0,(struct sockaddr FAR *)&clientAddr,(int FAR *)&fromlength);
if( SOCKET_ERROR != nRet )
{
char *pIPAddr = inet_ntoa(clientAddr.sin_addr);
if( NULL != pIPAddr )
{
WCHAR wzIPBuffer[32] = {0};
CXAStrToWide(pIPAddr, wzIPBuffer, 32);
AfxMessageBox(wzIPBuffer);
}
}
else
{
AfxMessageBox(L"Recv UDP Failed");
}
Sleep(1000);
}
closesocket(sClient);