Java Socket getPort() method

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.

Syntax

Parameter

NA

Return

The getPort() method either returns the port number to which the specified socket is connected or returns 0 if the socket is not connected.

Example 1

Test it Now

Output:

Port number: 1085

Example 2

Test it Now

Output:

Port number: 0

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1085
	at java.net.InetSocketAddress.checkPort(InetSocketAddress.java:143)
	at java.net.InetSocketAddress.(InetSocketAddress.java:188)
	at com.javaTpoint.JavaSocketGetPortExample3.main(JavaSocketGetPortExample3.java:12)




Latest Courses