Online Java Compiler By
JavaTpoint.com
import java.io.IOException; import java.net.*; public class JavaSocketGetLocalSocketAddressExample2 { public static void main(String[] args) throws IOException { Socket socket = new Socket(); //passing null InetAddress inetAddress=null; //the port should be greater or equal to 0, else it will throw an error int port=1085; //calling the constructor of the SocketAddress class SocketAddress socketAddress=new InetSocketAddress(inetAddress, port); //binding the socket with the inetAddress and port number socket.bind(socketAddress); socket.connect(socketAddress); //getPort() method will return the port number of this socket System.out.println("Local Port number: "+socket.getLocalPort()); //getLocalSocketAddress() returns the address of the endpoint to which this socket is bound //the default address returns the loopback SocketAddress System.out.println("Local socket address: "+socket.getLocalSocketAddress()); } }
Output