import java.io.IOException; import java.net.Socket; import java.net.InetSocketAddress; import java.net.SocketAddress; public class RemoteSocketAddressDemo { public static void main(String[] args) { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress("example.com", 80)); SocketAddress remoteAddress = socket.getRemoteSocketAddress(); System.out.println("Remote address: " + remoteAddress); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.IOException; import java.net.Socket; import java.net.InetSocketAddress; import java.net.SocketAddress; public class RemoteSocketAddressDemo { public static void main(String[] args) { try { Socket socket = new Socket("example.com", 80); SocketAddress remoteAddress = socket.getRemoteSocketAddress(); System.out.println("Remote address: " + remoteAddress); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }In this example, we create a new socket and connect it to an address (example.com on port 80) in the constructor itself. Then, we retrieve the remote socket address by calling getRemoteSocketAddress() method. Finally, we close the socket. Package library used: java.net