Java Socket .getLocalSocketAddress ()

Syntax

Socket.getLocalSocketAddress() has the following syntax.

public SocketAddress getLocalSocketAddress()

Example

In the following code shows how to use Socket.getLocalSocketAddress() method.


// w w  w. j a  va 2  s . c  o m
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Main {
  public static void main(String[] args) throws Exception {
    String serverName = args[0];
    int port = Integer.parseInt(args[1]);

    try {
      System.out.println("Connecting to " + serverName + " on port " + port);
      Socket client = new Socket(serverName, port);

      System.out.println("Just connected to " + client.getRemoteSocketAddress());

      OutputStream outToServer = client.getOutputStream();
      DataOutputStream out = new DataOutputStream(outToServer);
      out.writeUTF("Hello from " + client.getLocalSocketAddress());

      InputStream inFromServer = client.getInputStream();
      DataInputStream in = new DataInputStream(inFromServer);
      System.out.println("Server says " + in.readUTF());

      client.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}




















Home »
  Java Tutorial »
    java.net »




CookieManager
CookiePolicy
CookieStore
DatagramPacket
DatagramSocket
HttpCookie
HttpURLConnection
InetAddress
JarURLConnection
MulticastSocket
ServerSocket
Socket
SocketAddress
URI
URL
URLConnection
URLDecoder
URLEncoder