How to get the public IP of a user connected via socket?

7

I need to get the IP address of a user who will connect remotely to my program, and list it, the program itself is a chat where only the server will store the users IP address. The client connects via socket, how to proceed to capture the IP?

    
asked by anonymous 19.11.2014 / 01:00

1 answer

10

When you get the socket connected to the client, use the getInetAddress of the socket class, which will give you the IP (among other information) about the client that is connected to your program. With the getAddress method of class InetAddress you can get the client IP

public static void main(String[] args) {
    int portNumber = 8000;

    try {
        ServerSocket serverSocket = new ServerSocket(portNumber);
        Socket clientSocket = serverSocket.accept();
        InetAddress address = clientSocket.getInetAddress();
        byte[] ip = address.getAddress();
        System.out.print("Client IP: ");
        for (int i = 0; i < ip.length; i++) {
            System.out.print(ip[i] & 0xFF);
            if (i < ip.length - 1) System.out.print(".");
        }
        System.out.println();
        clientSocket.close();
        serverSocket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    
19.11.2014 / 01:52