利用java代码如何检测某端口号是否可用

利用java代码如何检测某端口号是否可用,第1张

很简单,给你写个例子:

//检测端口8080到8090哪些可用哪些不可用

for(int i = 8080i<8090i++){

try {

ServerSocket sskt = new ServerSocket(i)

System.out.println("端口[" +i + "]可用。")

} catch (IOException e) {

System.out.println("端口 [" + i + "] 被占用.")

}

}

比如我要监听1234这个端口,代码如下:String ip = "127.0.0.1"int port = 1234try {Socket socket = new Socket(ip, port)socket.setSoTimeout(5539900)java.io.OutputStream out = socket.getOutputStream()byte[] date = "hello world".getBytes()out.write(data)out.flush()byte[] buffer = new byte[1024]int len = -1java.io.FileOutputStream fout = new java.io.FileOutputStream("d:/response.txt")java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream()java.io.InputStream in = socket.getInputStream()while ((len = in.read(buffer, 0, buffer.length)) >0) {bout.write(buffer, 0, len)}in.close()bout.flush()bout.close()byte[] rdata = bout.toByteArray()System.out.println(new String(rdata))fout.write(rdata)fout.flush()fout.close()socket.close()} catch (UnknownHostException e) {e.printStackTrace()} catch (IOException e) {e.printStackTrace()}}服务器端的ServerSocket ss = new ServerSocket(1234)Socket socket=nullBufferedReader inPrintWriter outwhile (true) {socket = ss.accept()in = new BufferedReader(new InputStreamReader(socket.getInputStream()))out = new PrintWriter(socket.getOutputStream(),true)String line = in.readLine()out.println("you input is :" + line)out.close()in.close()socket.close()}

Socket

client

=

null

try{

client

=

new

Socket(IP,

port)

System.out.println("端口已开放")

client.close()

}catch(Exception

e){

System.out.println("端口未开放")

}

====================================================

这样就能正常捕获这个异常,不会阻止程序正常运行!


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/798264.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-08-27
下一篇2023-08-27

发表评论

登录后才能评论

评论列表(0条)

    保存