Java實(shí)現(xiàn)ping用Java來Ping機(jī)器,有兩個(gè)做法。一個(gè)是傳統(tǒng)的調(diào)用命令行執(zhí)行Ping命令的做法。這種做法的好處是速度快,比較可靠。缺點(diǎn) 是,不同的操作系統(tǒng),甚至Windows的不同版本,其執(zhí)行和返回結(jié)果格式都可能不同,造成跨平臺(tái)的不便以及代碼的啰嗦。第二個(gè)方法自然就是使用大家都熟 知的Java 5提供的InetAddress的isReachable方法。這個(gè)函數(shù)并非使用ICMP的ping,而是僅僅用TCP連一下7號(hào)端口而已。參考代 碼:public static boolean ping(String ip) {淘寶女裝夏裝新款
try {
InetAddress ipaddress = InetAddress.getByName(ip);
return ipaddress.isReachable(2000);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
SNMP ping
所謂SNMP Ping其實(shí)就是用SNMP去get一個(gè)非?;镜腛ID看對(duì)方有無反應(yīng)。如果能夠返回?cái)?shù)據(jù),說明這是一個(gè)SNMP節(jié)點(diǎn),可以通過SNMP配合MIB庫(kù)去 獲取更多的業(yè)務(wù)數(shù)據(jù)。例如磁盤、CPU、內(nèi)存、端口力量等等基本的信息,都有相關(guān)的SNMP MIB進(jìn)行定義。
SnmpContextv2c context = new SnmpContextv2c(ip, 161);
context.setCommunity("public");
BlockPdu pdu = new BlockPdu(context);
pdu.setRetryIntervals(new int[] { 1000 });
String sysUpTime = "1.3.6.1.2.1.1.3.0";
pdu.addOid(sysUpTime);
Object result = pdu.getResponseVariable();
代碼中用v2c,并假設(shè)community是public,超時(shí)時(shí)間1秒。獲取sysUpTime也就是設(shè)備啟動(dòng)時(shí)間。如果有返回,認(rèn)為節(jié)點(diǎn)存在且SNMP協(xié)議已啟動(dòng)。
try {
InetAddress ipaddress = InetAddress.getByName(ip);
return ipaddress.isReachable(2000);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
SNMP ping
所謂SNMP Ping其實(shí)就是用SNMP去get一個(gè)非?;镜腛ID看對(duì)方有無反應(yīng)。如果能夠返回?cái)?shù)據(jù),說明這是一個(gè)SNMP節(jié)點(diǎn),可以通過SNMP配合MIB庫(kù)去 獲取更多的業(yè)務(wù)數(shù)據(jù)。例如磁盤、CPU、內(nèi)存、端口力量等等基本的信息,都有相關(guān)的SNMP MIB進(jìn)行定義。
SnmpContextv2c context = new SnmpContextv2c(ip, 161);
context.setCommunity("public");
BlockPdu pdu = new BlockPdu(context);
pdu.setRetryIntervals(new int[] { 1000 });
String sysUpTime = "1.3.6.1.2.1.1.3.0";
pdu.addOid(sysUpTime);
Object result = pdu.getResponseVariable();
代碼中用v2c,并假設(shè)community是public,超時(shí)時(shí)間1秒。獲取sysUpTime也就是設(shè)備啟動(dòng)時(shí)間。如果有返回,認(rèn)為節(jié)點(diǎn)存在且SNMP協(xié)議已啟動(dòng)。