需要搞的这么复杂吗?试试这个行不行import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List;public class IPUtils { private static final List<String> innerIp = new ArrayList<String>(); /** * 获取所在内网所有IP * * @throws InterruptedException * @throws java.net.UnknownHostException */ public static void gainAllIp() throws InterruptedException, UnknownHostException, IOException { 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; if (InetAddress.getByName(ip).isReachable(1000)) { innerIp.add(ip); } } } public static String getLocalIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); return null; } } public static void main(String[] args) throws InterruptedException, IOException { gainAllIp(); } }不过我本机InetAddress.getLocalHost().getHostAddress();返回的是127.0.0.1,不知道你那能不能返回正确的IP。
ip段的计算方式有问题,并不是所有的网络子网掩码都是 255.255.255.0IpShow 的 run 方法内迭代循环输出 list 的内容,而 list 的内容可能在别的线程内被改变,所以直接迭代不可能是线程安全的,Collections.synchronizedList(list) 方法的 JavaDOC 里对迭代有特别交代ping 网络地址应该有更好的API可以用
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;public class IPUtils { private static final List<String> innerIp = new ArrayList<String>(); /**
* 获取所在内网所有IP
*
* @throws InterruptedException
* @throws java.net.UnknownHostException
*/
public static void gainAllIp() throws InterruptedException, UnknownHostException, IOException {
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;
if (InetAddress.getByName(ip).isReachable(1000)) {
innerIp.add(ip);
}
}
} public static String getLocalIP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
} public static void main(String[] args) throws InterruptedException, IOException {
gainAllIp();
}
}不过我本机InetAddress.getLocalHost().getHostAddress();返回的是127.0.0.1,不知道你那能不能返回正确的IP。