Java Socket getPort() method25 Mar 2025 | 2 min read The getPort() method of Java Socket class returns the remote port number to which the socket is connected. This method will return the port number even after the socket is closed. SyntaxParameterNA ReturnThe getPort() method either returns the port number to which the specified socket is connected or returns 0 if the socket is not connected. Example 1Output: Port number: 1085 Example 2Output: Port number: 0 Example 3Output: Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1085 at java.net.InetSocketAddress.checkPort(InetSocketAddress.java:143) at java.net.InetSocketAddress. Next TopicJava Socket Class |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India