65,211
社区成员
发帖
与我相关
我的任务
分享
//改正后的代码:
//自动发现在线设备,思想是:输入一网段IP,如:192。168。1。2---192。168。1。254,便显示在线设备的IP地址,
//由于会是多个IP地址,所以用二维指针。
#include "snmp_pp/snmp_pp.h"
#include "snmp_pp/Oid.h"
#include <iostream>
#include <cstring>
using namespace std;
char **scan(char *startip, char *endip)
{
char **p=new char*[255];
int status, first, last, i;
int sum=0; //用来统计网段中扫描的IP数目,以在主函数中使用;
char *c=new char[16];
memset(c,NULL,16);
char *firstr1, *firstr2, *firstr3, *firstr4, *lasstr1, *lasstr2, *lasstr3, *lasstr4;
char str1[4], ip[16]; //注意此处应为4。
firstr1 = strtok(startip, ".");
firstr2 = strtok(NULL, ".");
firstr3 = strtok(NULL, ".");
firstr4 = strtok(NULL, ".");
lasstr1 = strtok(endip, ".");
lasstr2 = strtok(NULL, ".");
lasstr3 = strtok(NULL, ".");
lasstr4 = strtok(NULL, ".");
first = atoi(firstr4); //得到起始地址的最后一位数;
last = atoi(lasstr4); //得到终止地址的最后一位数;
for (i=first; i<=last; i++)
{
itoa(i, str1, 10);
strcat(ip, firstr1);
strcat(ip, ".");
strcat(ip, firstr2);
strcat(ip, ".");
strcat(ip, firstr3);
strcat(ip, ".");
strcat(ip, str1); //得到IP地址;
Snmp::socket_startup();
snmp_version version=version1;
Snmp snmp(status,0,false);
Pdu pdu;
Vb vb;
vb.set_oid((Oid)"1.3.6.1.2.1.1.7.0");
pdu+=vb;
CTarget ctarget((IpAddress)ip); //设置网管目标
ctarget.set_version(version);
ctarget.set_retry(1); //UDP包重发次数,默认值为1
ctarget.set_timeout(1);//超时时间设为1,注:总等待时间=超时值*(重传次数+1)
ctarget.set_readcommunity("public");
SnmpTarget* target;
target=&ctarget;
status=snmp.get(pdu,*target);
if(status==SNMP_CLASS_SUCCESS)//如果返回值成功,则说明该设备存在,把IP输入以供显示
{
++sum;
p[sum]=new char[16];
memset(p[sum],NULL,16);
strcpy(p[sum],ip);
}
}
itoa(sum,c,10);
p[0]=new char[16];
memset(p[0],NULL,16);
strcpy(p[0],c);
delete []c;
Snmp::socket_cleanup();
return &p[0]; //返回存在IP的数目;以供主函数调用;
}
void main()
{
int s;
char sip[16]="222.18.147.155";
char eip[16]="222.18.147.162";
char **q;
q=scan(sip,eip);
s=atoi(q[0]);
for(int i=0;i<s;i++)
{
cout<<"设备的IP地址为:"<<q[i+1]<<endl;
}
for(int j=0;j<s;j++)
{
delete[]q[j];
}
delete[]q;
}
q=scan(sip,eip);
s=atoi(q[0]);
看看q是多少,s是多少?