在Windows或者Linux操作系統中,獲取多網卡信息,可通過執行命令方式獲取,具體如下:
public Vector<String> getServerIps()
{
Vector<String> address = new Vector<String>();
String linuxKey = "inet";
String window7Key = "IPv4";
String windowKey = "IP Address";
String os = System.getProperty("os.name");
if (os != null)
{
if (os.startsWith("Windows"))
{
try
{
ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");
Process p = pb.start();
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null)
{
if ((line.indexOf(window7Key) != -1)
|| (line.indexOf(windowKey) != -1))
{
int index = line.indexOf(":");
int indexLast = line.indexOf("(");
String sbstr = null;
if (indexLast == -1)
{
sbstr = line.substring(index + 1).trim();
}
else
{
sbstr = line.substring(index + 1, indexLast).trim();
}
if (!sbstr.equals("127.0.0.1"))
{
address.add(sbstr);
}
}
}
br.close();
return address;
}
catch (IOException e)
{
String localIp = "";
try
{
String localHost = InetAddress.getLocalHost().toString();
localIp = localHost.split("/")[1];
}
catch (UnknownHostException ex)
{
localIp = "127.0.0.1";
}
address.add(localIp);
}
}
else if (os.startsWith("Linux"))
{
try
{
ProcessBuilder pb = new ProcessBuilder("ifconfig");
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null)
{
if (line.indexOf(linuxKey) != -1)
{
int index = line.indexOf(":");
String sbstr = line.substring(index + 1).trim();
if (!sbstr.equals("127.0.0.1"))
{
address.add(sbstr);
}
}
}
br.close();
return address;
}
catch (IOException ex)
{
String localIp = "";
try
{
String localHost = InetAddress.getLocalHost().toString();
localIp = localHost.split("/")[1];
}
catch (UnknownHostException eu)
{
localIp = "127.0.0.1";
}
address.add(localIp);
}
}
}
return address;
}