日期:2014-05-20 浏览次数:20696 次
package org.sz.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class IPUtils {
/**
* 获取所在内网所有IP
* @param args
* @throws InterruptedException
*/
public static void gainAllIp() throws InterruptedException {
final List<String> innerIp = Collections.synchronizedList(new ArrayList<String>());
final CyclicBarrier barrier = new CyclicBarrier(255, new IpShow(innerIp));
String hostAddress = getLocalIP();
int pos = hostAddress.lastIndexOf(".");
String wd = hostAddress.substring(0, pos + 1);
for (int i = 1; i <= 255; i++) {
String ip = wd + i;
PingIpThread thread = new IPUtils.PingIpThread(ip, barrier, innerIp);
thread.start();
}
}
public static class IpShow implements Runnable {
private List<String> innerIp;
public IpShow(List<String> innerIp) {
this.innerIp = innerIp;
}
@Override
public void run() {
System.out.println(innerIp.size());
for (String ip : innerIp) {
System.out.println(ip);
}
}
}
public static class PingIpThread extends Thread {
private String ip;
private CyclicBarrier barrier;
private List<String> list;
public PingIpThread(String ip, CyclicBarrier barrier, List<String> list) {
this.ip = ip;
this.barrier = barrier;
this.list = list;
}
public void run() {
try {
String cmd = "ping " + ip + " -n 1";
Process process = Runtime.getRuntime().exec(cmd);
//process.waitFor();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String line = in.readLine();
while (line !=null) {
if (line !=null && !line.equals("")) {
if (line.substring(0, 2).equals("来自")
|| (line.length() > 10 && line.substring(0, 10)
.equals("Reply from"))) {
list.add(ip);
}
}
line = in.readLine();
}
} catch(IOException e) {
}
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
try {
barrier.await();
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (BrokenBarrierException bbe) {
bbe.printStackTrace();
}
}
}
public static String getLocalIP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
}
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
}
public static String getCanonicalHostName() {