下面的代码显示子网掩码。在具有多个网络连接的计算机上(例如具有无线和 Cat-5 以太网连接的笔记本电脑),它可能会写入两次子网掩码,因为客户端可以有两个不同的 IP 地址。
String os = System.getProperty("os.name");
try {
if(os.indexOf("Windows 7")>=0) {
Process process = Runtime.getRuntime().exec("ipconfig");
process.waitFor();
InputStream commandOut= process.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(commandOut));
String line;
while((line = in.readLine()) !=null) {
if(line.indexOf("Subnet Mask")>=0) {
int colon = line.indexOf(":");
System.out.println(line.substring(colon+2));
}
}
}
catch(IOException ioe) { }
catch(java.lang.InterruptedException utoh) { }
在有线和无线连接都处于活动状态的笔记本电脑上,我得到以下输出:255.255.254.0 255.255.254.0
当我关闭无线连接时,正如预期的那样,我只看到有线以太网链路的一条输出。