YouTip LogoYouTip

Net Port

[![Image 1: Java Examples](#) Java Examples](#) The following example demonstrates how to check if a port is already in use: ## Example import java.net.*; import java.io.*; public class Main{public static void main(String[]args){Socket Skt; String host = "localhost"; if(args.length>0){host = args; }for(int i = 0; i<1024; i++){try{System.out.println("Checking "+ i); Skt = new Socket(host, i); System.out.println("Port " + i + " is already in use"); }catch(UnknownHostException e){System.out.println("Exception occured"+ e); break; }catch(IOException e){}}}} The output of the above code is: ……Checking 17Checking 18Checking 19Checking 20Checking 21Port 21 is already in useChecking 22Checking 23Checking 24…… You can also specify the port of a host: ## Main.java File import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketTimeoutException; public class Main{public static void main(String[]args){log(isSocketAliveUitlitybyCrunchify("localhost", 80)); log(isSocketAliveUitlitybyCrunchify("localhost", 8080)); log(isSocketAliveUitlitybyCrunchify("localhost", 8081)); log(isSocketAliveUitlitybyCrunchify(".com", 80)); log(isSocketAliveUitlitybyCrunchify(".com", 443)); log(isSocketAliveUitlitybyCrunchify(".com", 81)); } @param @param @return public static boolean isSocketAliveUitlitybyCrunchify(String hostName, int port){boolean isAlive = false; SocketAddress socketAddress = new InetSocketAddress(hostName, port); Socket socket = new Socket(); int timeout = 2000; log("hostName: " + hostName + ", port: " + port); try{socket.connect(socketAddress, timeout); socket.close(); isAlive = true; }catch(SocketTimeoutException exception){System.out.println("SocketTimeoutException " + hostName + ":" + port + ". " + exception.getMessage()); }catch(IOException exception){System.out.println("IOException - Unable to connect to " + hostName + ":" + port + ". " + exception.getMessage()); }return isAlive; }private static void log(String string){System.out.println(string); }private static void log(boolean isAlive){System.out.println("Is it really in use: " + isAlive + "n"); }} The output of the above code is: hostName: localhost, port: 80IOException - Unable to connect to localhost:80. Connection refused Is it really in use: true hostName: localhost, port: 8080IOException - Unable to connect to localhost:8080. Connection refused Is it really in use: false hostName: localhost, port: 8081IOException - Unable to connect to localhost:8081. Connection refused Is it really in use: false hostName: .com, port: 80Is it really in use: true hostName: .com, port: 443Is it really in use: true hostName: .com, port: 81SocketTimeoutException .com:81. connect timed outIs it really in use: false [![Image 2: Java Examples](#) Java Examples](#)
← Cpp Friend FunctionsNet Webpage β†’