您的位置:首页 > 编程语言 > Java开发

Windows下使用JAVA检测端口是否已被占用

2013-07-12 14:44 961 查看
第一种方法:使用Socket

 

public  boolean isPortUsing(String hostIp,int port){

        boolean flag = false;

        try {

            InetAddress address = InetAddress.getByName(hostIp);

            new Socket(address,port);

            flag = true;

        } catch (UnknownHostException e) {

           

        }catch (IOException e) {

            System.out.println("the port cannot be connected!");

        }

        return flag;

    }

 

第二种方法:使用dos命令

public boolean isPortRunning(String port){

        try {

            Process process = Runtime.getRuntime().exec("cmd /c netstat -an | findstr "+port);

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String lineString = "" ;

            boolean flag = false;

            while ((lineString = reader.readLine()) != null) {

                flag = regexFind(lineString, port);

                if(flag){

                    return flag;

                }

            }

        } catch (IOException e) {

           

        }

        return false;

    }

   

    public boolean regexFind(String lineString,String port){

        String regex=":(\\d+)\\s+\\d+";

        Matcher matcher = Pattern.compile(regex).matcher(lineString);

        while(matcher.find()){

            if(port.trim().equals(matcher.group(1).trim())){

                return true;

            }

        }

        return false;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: