UDP获取服务器IP地址?

a3622041 2017-09-05 02:00:59

WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}

if ( LOBYTE( wsaData.wVersion ) != 2 ||HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup( );
return;
}
SOCKET sSrv;
sockaddr_in addrto;
WSADATA wsdata;
BOOL bsocket;
char buff[255] = "";
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(8900); // 与服务器端的相同
//设置该套接字为广播类型
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) )
MessageBox(NULL,"Send UDP Failed","",MB_OK);
while(true)
{
// 接收数据
int nSendSize = recvfrom(sSrv, buff, 255, 0, (SOCKADDR*)&addrto,&nLen);
if(SOCKET_ERROR == nSendSize)
{
int err = WSAGetLastError();
printf("\"recvfrom\" error! error code is %d\n", err);
return ;
}
buff[nSendSize] = '\0';
printf("received ip: %s\n", buff);
}
...全文
1567 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
worldy 2017-09-07
  • 打赏
  • 举报
回复
recvfrom The Windows Sockets recvfrom function receives a datagram and stores the source address. int recvfrom ( SOCKET s, char FAR* buf, int len, int flags, struct sockaddr FAR* from, int FAR* fromlen ); Parameters s [in] A descriptor identifying a bound socket. buf [out] A buffer for the incoming data. len [in] The length of buf. flags [in] An indicator specifying the way in which the call is made. from [out] An optional pointer to a buffer that will hold the source address upon return. fromlen [in/out] An optional pointer to the size of the from buffer. 检查nSendSize是否为大于0的数,如果是,则from参数应该不会空
a3622041 2017-09-07
  • 打赏
  • 举报
回复
引用 2 楼 worldy 的回复:
int nSendSize = recvfrom(sSrv, buff, 255, 0, (SOCKADDR*)&addrto,&nLen); 红色包含有返回的发送方的地址和端口信息
断点看那个值是空的
worldy 2017-09-05
  • 打赏
  • 举报
回复
int nSendSize = recvfrom(sSrv, buff, 255, 0, (SOCKADDR*)&addrto,&nLen); 红色包含有返回的发送方的地址和端口信息
a3622041 2017-09-05
  • 打赏
  • 举报
回复
addrto.sin_port=htons(8900); 断电看 这个值为什么为addrto.sin_port=50210

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧