Java Socket bind() method

The bind() method of Java Socket class binds the socket to a local address. If the specified address is null, then the system will automatically pick up a port number and a valid local address to bind with the socket.

Syntax

Parameter

The parameter 'bindpoint' represents the SocketAddress to bind.

Return

NA

Throws

IOException - if the bind operation fails, or if the socket is already bound.

IllegalArgumentException - if the bindpoint is a SocketAddress subclass not supported by this socket.

SecurityException - if the security manager exists and its checkListen method doesn't allow the bind to the local port.

Example 1

Test it Now

Output:

Inet address: null
Port number: 1085

Example 2

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.JavaSocketBindExample2.main(JavaSocketBindExample2.java:12)

Example 3

Test it Now

Output:

Exception in thread "main" java.net.SocketException: Socket is closed
	at java.net.Socket.bind(Socket.java:625)
	at com.javaTpoint.JavaSocketBindExample3.main(JavaSocketBindExample3.java:17)




Latest Courses