扫描局域网中的ip需要依靠DOS命令中的ping和arp指令
1. ping网段中的1~255 ip这样arp表就被更新
ping -w 2 -n 1 192.168."+j+"."+i
2. 读取arp表中的ip
arp -a
Runtime类exec()可以执行DOS命令并返回Proecess类
Process类getInputStream可以获取DOS中的结果,再进行整理就可以获得ip了
String类的split()中正则表达式的点".",属于关键字,需要特殊表达 "\\."
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class IPScan {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//Runtime.getRuntime().exec("ping 192.168.1.1").destroy();
//Runtime.getRuntime().exec("for /l %i in (1,1,255) do " +
// "(ping -w 2 -n 1 192.168.1.%i)").destroy();
String localIP=InetAddress.getLocalHost().getHostAddress();
String[] net=localIP.split("\\.");
int j=Integer.parseInt(net[2]);
for(int i=1;i<256;i++){
Runtime.getRuntime().exec("ping -w 2 -n 1 192.168."+j+"."+i).destroy();
}
Process p=Runtime.getRuntime().exec("arp -a");
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
br.readLine();
br.readLine();
br.readLine();
String temp=null;
while(((temp=br.readLine())!=null&&!temp.isEmpty())){
System.out.println(temp.trim().split(" ")[0]);
}
//String localIP=InetAddress.getLocalHost().getHostAddress();
//String[] net=localIP.split("\\.");
//System.out.println(net[2]);
//System.out.println(InetAddress.getLocalHost().getHostAddress());
p.destroy();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}