【发布时间】:2014-06-04 09:40:52
【问题描述】:
我试图从 java 中的 ifconfig 命令获取所有 inet、bcast 和掩码 IP。但我正在努力使正则表达式正确。
这是我天真的尝试:我尝试了几种使用“\s”和“”作为空格的变体。
String string;
try {
// discover ip addresses
writer.write("Discovering available network connections...\n\n");
System.out.println("-------------------------");
// String ifconfigCmd = "/sbin/ifconfig | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1 }'";
String ifconfigCmd = "ifconfig";
System.out.println("executing `" + ifconfigCmd + "`");
Process ifconfigProc = Runtime.getRuntime().exec(ifconfigCmd);
BufferedReader ifconfigProcReader = new BufferedReader(new InputStreamReader(ifconfigProc.getInputStream()));
// read output of ifconfig command
HashSet<String> subnets = new HashSet<>();
String ipaddress, inet, bcast, mask;
String ipaddressPattern = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
while ((ipaddress = ifconfigProcReader.readLine()) != null) {
System.out.println("ifconfig : " + ipaddress);
String pStr = ".*(inet addr:(?<inet>" + ipaddressPattern + "))?.*(Bcast:(?<bcast>" + ipaddressPattern + "))?.*(Mask:(?<mask>" + ipaddressPattern + "))?.*";
Matcher m = Pattern.compile(pStr).matcher(ipaddress);
if (m.matches()) {
try {
inet = m.group("inet");
System.out.println("inet : " + inet);
if (inet != null) {
int i = inet.lastIndexOf(".");
System.out.println("last index of .: " + i);
if (i >= 0) {
ipaddress = ipaddress.substring(0, i+1) + "*";
System.out.println("subnet : " + ipaddress);
subnets.add(ipaddress);
}
}
}
catch (IllegalStateException e) {}
try {
bcast = m.group("bcast");
System.out.println("bcast : " + bcast);
}
catch (IllegalStateException e) {}
try {
mask = m.group("mask");
System.out.println("mask : " + mask);
}
catch (IllegalStateException e) {}
}
}
有人可以帮忙吗?
谢谢。
【问题讨论】: