is Host Port Available - Java Network

Java examples for Network:Http

Description

is Host Port Available

Demo Code


//package com.java2s;
import java.io.IOException;
import java.net.Socket;

public class Main {
    public static void main(String[] argv) throws Exception {
        String host = "java2s.com";
        int port = 2;
        System.out.println(isPortAvailable(host, port));
    }/*from w ww  .jav a  2 s . co  m*/

    public static boolean isPortAvailable(String host, int port) {
        Socket socket = null;
        boolean available = false;
        try {
            socket = new Socket(host, port);
            available = true;
        } catch (IOException e) {
            // no-op
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // no-op
                }
            }
        }
        return available;
    }
}

Related Tutorials