Java Socket getLocalPort() method

The getLocalPort() method of Java Socket class returns the local port number to which the specified socket is bound. If the socket was being closed, this method will return the connected port number after the socket is closed.

Syntax

Parameter

NA

Return

The getLocalPort () method either returns the local port number to which the socket is connected, or returns -1 if the socket is not bounded.

Example 1

Test it Now

Output:

Port number: 1085

Example 2

Test it Now

Output:

Port number: -1

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.JavaSocketGetLocalPortExample3.main(JavaSocketGetLocalPortExample3.java:13)




Latest Courses