如何检查端口是否在使用中? [英] How can I check whether a port is in use?

查看:95
本文介绍了如何检查端口是否在使用中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我正在使用cvs api,并且一次不能发送2条cvs命令.
我要发送一个cvs命令并等待直到端口不再使用,然后再发送第二个cvs命令.这两个命令发生在2个不同的踏板上.对线程了解不多,所以我的猜测是检查端口是否在使用中.

任何人都知道我可以使用的Class +函数吗?

Hi all

I''m using a cvs api and cannot send 2 cvs commands at a time.
I want to send the one cvs command and wait until the port is no longer in use before sending the second cvs command. The two commands happens on 2 different treads. Don''t know much about threads so my guess is checking whether the port is in use.

Anyone know about a Class + function which I can make use of?

推荐答案

我不是Java语言的人,但是不管编程语言/库是什么,要检查IP地址上的端口是否可用,请尝试连接到该端口.端口扫描软件就是这样做的.您必须在Java中执行相同的操作(搜索Java的套接字类).
I am not a Java person, but irrespective of the programming language/library, the one way to check if a port on an IP address is available is to try connecting to it. That''s what''s done by port scanning software. You''ll have to do the same in Java (search for Java''s socket classes).


我宁愿同步线程,也不愿检查端口是否打开(同时检查您将消耗比线程上应用的同步机制昂贵得多的资源(操作系统套接字).
问候
I would rather synchronize the threads than checking if a port is opened or not (while checking you''ll consume resources (OS sockets) that are much more expensive than synchronization mechanism applied on threads).
Regards


谢谢,
我确实偶然遇到了一个检查端口是否可用的漂亮函数:

Thanks all,
I did stumble accross a nifty function that checks whether a port is available or not:

public static boolean port_available(int port)
  {
    ServerSocket ss = null;
    DatagramSocket ds = null;
    try
    {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    }
    catch (IOException e)
    {     }
    finally
    {
      if (ds != null)
      {
        ds.close();
      }
      if (ss != null)
      {
        try
        {
          ss.close();
        }
        catch (IOException e)
        {
          /* should not be thrown */
        }
      }
    }
    return false;
  }


这篇关于如何检查端口是否在使用中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆