//#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#define GET_HOST_COMMAND "GetIPAddr"
const int MAX_BUF_LEN = 255;
#define SERVER_PORT 12811
typedef struct tagIPInfo
{
char ip[30];
}IPInfo;
bool GetLocalIPs(IPInfo* ips,int maxCnt,int* cnt)
{
//1.初始化wsa
WSADATA wsaData;
int ret=WSAStartup(MAKEWORD(2,2),&wsaData);
if (ret!=0)
{
return false;
}
//2.获取主机名
char hostname[256];
ret=gethostname(hostname,sizeof(hostname));
if (ret==SOCKET_ERROR)
{
return false;
}
//3.获取主机ip
HOSTENT* host=gethostbyname(hostname);
if (host==NULL)
{
return false;
}
//4.逐个转化为char*并拷贝返回
*cnt=host->h_length<maxCnt?host->h_length:maxCnt;
for (int i=0;i<*cnt;i++)
{
in_addr* addr=(in_addr*)*host->h_addr_list;
strcpy(ips[i].ip,inet_ntoa(addr[i]));
}
return true;
}
bool GetLocalIP(char* ip)
{
//1.初始化wsa
WSADATA wsaData;
int ret=WSAStartup(MAKEWORD(2,2),&wsaData);
if (ret!=0)
{
return false;
}
//2.获取主机名
char hostname[256];
ret=gethostname(hostname,sizeof(hostname));
if (ret==SOCKET_ERROR)
{
return false;
}
//3.获取主机ip
HOSTENT* host=gethostbyname(hostname);
if (host==NULL)
{
return false;
}
//4.转化为char*并拷贝返回
strcpy(ip,inet_ntoa(*(in_addr*)*host->h_addr_list));
return true;
}
bool doServer(){
int m_nPort = SERVER_PORT;
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 false;
}
//用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));
int nAddrLen = sizeof(SOCKADDR);
char buf[256] = {0};
int fromlength=sizeof(SOCKADDR);
printf("the server is start.\n");
char ipaddr[30] = {0};
char buff[MAX_BUF_LEN] = "";
if (GetLocalIP(ipaddr))
{
sprintf(buff, "my ip is:%s", ipaddr);
}
else
{
sprintf(buff, "%s", "my ip is:******");
}
//有多个ip地址的时候
//IPInfo ips[10];
//int len1 = 0;
//GetLocalIPs(ips, 10,&len1);
while(true)
{
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);
printf("clientAddr: %s\n", pIPAddr);
printf("receive command: %s\n", buf);
}
if (strcmp(buf,GET_HOST_COMMAND) != 0)
{
printf("the command not valid and was ignored.\n", buf);
continue;
}
// 发送数据
int nSendSize = sendto(sClient, buff, strlen(buff), 0, (SOCKADDR*)&clientAddr, nAddrLen);
if(SOCKET_ERROR == nSendSize)
{
int err = WSAGetLastError();
printf("\"sendto\" error!, error code is %d\n", err);
return false;
}
}
else
{
//AfxMessageBox(L"Recv UDP Failed");
}
Sleep(1000);
}
closesocket(sClient);
return true;
}
int main()
{
if (!doServer())
{
printf("sever returned an error");
return -1;
}
return 0;
}
/*
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
// 启动socket api
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return -1;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup( );
return -1;
}
// 创建socket
SOCKET connect_socket;
connect_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(INVALID_SOCKET == connect_socket)
{
err = WSAGetLastError();
printf("\"socket\" error! error code is %d\n", err);
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(3779);
sin.sin_addr.s_addr = INADDR_BROADCAST;
bool bOpt = true;
//设置该套接字为广播类型
setsockopt(connect_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));
int nAddrLen = sizeof(SOCKADDR);
char buff[MAX_BUF_LEN] = "";
int nLoop = 0;
while(1)
{
nLoop++;
sprintf(buff, "%8d", nLoop);
// 发送数据
int nSendSize = sendto(connect_socket, buff, strlen(buff), 0, (SOCKADDR*)&sin, nAddrLen);
if(SOCKET_ERROR == nSendSize)
{
err = WSAGetLastError();
printf("\"sendto\" error!, error code is %d\n", err);
return -1;
}
printf("Send: %s\n", buff);
Sleep(500);
}
return 0;
}
*/
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
代码描述,参见博客:http://blog.csdn.net/dxzysk/article/details/55506450 本文是windows版,VC++,在VS2010环境下调试成功。有时候需要搜索网络中的设备,机器,服务器等,这就要要用到UDP广播的方式,发送广播命令,广播给网络中的每一个主机,该主机搜到广播命令后,立刻发送给请求端自己的设备信息,这里以IP信息为例子。
资源推荐
资源详情
资源评论
收起资源包目录
DemoUDPBroadcast - csdn.rar (83个子文件)
DemoUDPBroadcast - csdn
UDPClient
Client.dsp 3KB
client.plg 1KB
Client.vcxproj.user 143B
Client.vcxproj 6KB
Client.cpp 4KB
client.opt 53KB
Debug
vc100.idb 363KB
Client.obj 28KB
Client.pdb 1.62MB
CL.write.1.tlog 488B
CL.read.1.tlog 14KB
mt.read.1.tlog 214B
rc.write.1.tlog 390B
Client.log 3KB
rc.read.1.tlog 382B
link.3316.write.1.tlog 2B
Client.Build.CppClean.log 3KB
Client.ilk 924KB
mt.command.1.tlog 434B
cl.command.1.tlog 792B
link-cvtres.read.1.tlog 2B
Client.exe.intermediate.manifest 381B
Client.lastbuildstate 96B
Client.exe.embed.manifest.res 472B
link.write.1.tlog 1KB
link.3316-cvtres.write.1.tlog 2B
link-cvtres.write.1.tlog 2B
Client.exe.embed.manifest 406B
link.command.1.tlog 2KB
rc.command.1.tlog 626B
link.read.1.tlog 4KB
Client_manifest.rc 208B
link.3316-cvtres.read.1.tlog 2B
mt.write.1.tlog 410B
link.3316.read.1.tlog 2B
Client.exe 389KB
vc100.pdb 100KB
DemoUDPBroadcast.ncb 49KB
DemoUDPBroadcast.sln 2KB
DemoUDP.opt 58KB
DemoUDPBroadcast.opt 58KB
DemoUDPBroadcast.sdf 27.14MB
UDPServer
Server.plg 1KB
Server.cpp 5KB
Server.vcxproj 7KB
Server.opt 53KB
Server.vcxproj.user 143B
Server.dsp 3KB
Debug
vc100.idb 515KB
link.7936-cvtres.read.1.tlog 2B
CL.write.1.tlog 488B
Server.lastbuildstate 96B
CL.read.1.tlog 21KB
Server.exe.intermediate.manifest 381B
mt.read.1.tlog 214B
rc.write.1.tlog 390B
rc.read.1.tlog 382B
Server.pdb 1.77MB
Server.Build.CppClean.log 3KB
mt.command.1.tlog 434B
link.7936.read.1.tlog 2B
cl.command.1.tlog 792B
link-cvtres.read.1.tlog 2B
link.7936.write.1.tlog 2B
Server.exe.embed.manifest 406B
link.write.1.tlog 1KB
Server.obj 70KB
Server.ilk 967KB
link-cvtres.write.1.tlog 2B
Server.exe 391KB
Server.log 4KB
link.command.1.tlog 2KB
rc.command.1.tlog 626B
link.read.1.tlog 4KB
Server_manifest.rc 208B
mt.write.1.tlog 410B
Server.exe.embed.manifest.res 472B
link.7936-cvtres.write.1.tlog 2B
vc100.pdb 236KB
DemoUDPBroadcast.suo 14KB
DemoUDP.ncb 49KB
ipch
client-f04a8b14
client-55af5795.ipch 31.69MB
server-3fe33a44
server-bcbd38ad.ipch 43.81MB
共 83 条
- 1
资源评论
- qq_360173042023-07-03#毫无价值
- LIN137501075742018-03-12谢谢楼主,非常有用!
- anlisy2017-05-19效果一般吧
dxzysk
- 粉丝: 41
- 资源: 22
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功