4

Although I searched about it I couldn't find an answer.

Let's say I have the following Java code:

    ServerSocket serve = null;

    try {
        server = new ServerSocket(5567);
    } catch (IOException e) {
        System.err.println("Problem with port 5567");
        System.exit(1);
    }

    Socket clientSocket = null;
    try {
        clientSocket = server.accept();
    } catch (IOException e) {
        System.exit(1);
    }

When server.accept() is being called the program blocks until someone connects to my server. Is there a way, to be able to find the IP of the program/user who connects to my server?

CoolBeans
  • 20,654
  • 10
  • 86
  • 101
Navorkos
  • 43
  • 1
  • 3

1 Answers1

4

Try

Socket clientSocket = null;
    try {
        clientSocket = server.accept();
        System.out.println("Connected from " + clientSocket .getInetAddress() + " on port "
             + clientSocket .getPort() + " to port " + clientSocket .getLocalPort() + " of "
             + clientSocket .getLocalAddress());
    } catch (IOException e) {
        System.exit(1);
    }
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • This seems back to front. The 'from' ip:port is given by getInetAddress() : getPort(). The local ip:port is given by getLocalAddress() : getLocalPort(). – user207421 Feb 15 '11 at 03:54