Java 从ifconfig获取inet、bcast和mask

Java 从ifconfig获取inet、bcast和mask,java,regex,Java,Regex,我正在尝试从java中的ifconfig命令获取任何和所有inet、bcast和mask IP。但是我正在努力使正则表达式正确 这是我天真的尝试:我已经尝试了使用“\s”和“”作为空格的几种变体 String string; try { // discover ip addresses writer.write("Discovering available network connections...\n\n"); System.out.println("--------

我正在尝试从java中的ifconfig命令获取任何和所有inet、bcast和mask 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) {}
        }
    }
字符串;
试一试{
//发现ip地址
writer.write(“发现可用的网络连接…\n\n”);
System.out.println(“---------------------------”);
//字符串ifconfigCmd=“/sbin/ifconfig | grep”inet addr:'| cut-d:-f2 | awk'{print$1}';
字符串ifconfigCmd=“ifconfig”;
System.out.println(“正在执行`+ifconfigCmd+`”);
进程ifconfigProc=Runtime.getRuntime().exec(ifconfigCmd);
BufferedReader ifconfigProcReader=新的BufferedReader(新的InputStreamReader(ifconfigProc.getInputStream());
//读取ifconfig命令的输出
HashSet子网=新HashSet();
字符串ipaddress、inet、bcast、掩码;
字符串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])$”;
而((ipaddress=ifconfigProcReader.readLine())!=null){
System.out.println(“ifconfig:+ipaddress”);
字符串pStr=“*(inet地址:(?“+ipaddressPattern+”)))。*(Bcast:(?“+ipaddressPattern+”)))。*(掩码:(?“+ipaddressPattern+”))));
Matcher m=Pattern.compile(pStr).Matcher(ipaddress);
如果(m.matches()){
试一试{
inet=m.group(“inet”);
System.out.println(“inet:+inet”);
如果(inet!=null){
int i=inet.lastIndexOf(“.”);
System.out.println(“最后的索引:”+i);
如果(i>=0){
ipaddress=ipaddress.substring(0,i+1)+“*”;
System.out.println(“子网:+ipaddress”);
子网。添加(IP地址);
}
}
}
捕获(非法状态){}
试一试{
bcast=m组(“bcast”);
System.out.println(“bcast:+bcast”);
}
捕获(非法状态){}
试一试{
掩码=m.组(“掩码”);
System.out.println(“掩码:+掩码”);
}
捕获(非法状态){}
}
}
有人能帮忙吗


谢谢。

我有一种方法可以做到:

    ....
    inet = null;
    bcast = null;
    mask = null;
    ....
    while ((ipaddress = ifconfigProcReader.readLine()) != null) {
            if (inet != null && bcast != null && mask != null)
            {
                break;
            }
            if (inet == null)
            {
                inet = search("inet addr:[0-9.]+", ipaddress, "inet addr:");
            }
            if (bcast == null)
            {
                bcast = search("Bcast:[0-9.]+", ipaddress, "Bcast:");
            }
            if (mask == null)
            {
                mask = search("Mask:[0-9.]+", ipaddress, "Mask:");
            }
        }
    //check if you have got all the ip address populated
    // in inet, bcast, mask
    ....
    ....


        private String search(String regex, String line, String removeString)
        {
            Pattern compiledPattern = Pattern.compile(regex);
            Matcher matcher = compiledPattern.matcher(line);
            String ipAddress = null;
            if (matcher.find())
            {
                ipAddress = matcher.group().replaceFirst(removeString, "");
            }
            return ipAddress;
        }
您也可以像这样使用正则表达式:

....
regex = "(inet addr:)([0-9.]+)";
.....

if(matcher.find()){
    ipAddress = matcher.group(2);
}

谢谢。我也喜欢它把正则表达式分解成更小的部分。更容易阅读和理解。谢谢!