Korvo
Korvo

Reputation: 9734

Server-Address in client-side java

I'm trying to get the address that the client has accessed my server.

I got it partially with the function: [SOCKET].getInetAddress().getHostName()

But the client access http://127.0.0.1:8890 function [SOCKET].getInetAddress().getHostName() return it localhost instead of 127.0.0.1.

I need the server to get the address as the client that sent data as COOKIES not lost any chance redirection occurs (302 Found or 301 Moved Permanently).

I searched everywhere, especially in the OS, but I do not know what search terms to use (if someone already asked this question), so excuse me if this is a duplicate.

My code:

package com.[PACKAGE];

/*web server*/
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Locale;

/*Err*/
//import java.io.IOException;

public class miniWebServer {
    private int port;
    private ServerSocket mySocket;
    private Socket remote;
    private Thread trd;

    public miniWebServer(int _port) {
        port = _port;
        initServer();
    }

    private void initServer(){
        trd = new Thread(new Runnable(){
            @Override
            public void run(){
                try {
                    //Criar socket
                    mySocket = new ServerSocket(port);
                    System.out.println("Conected!");
                    OK();
                } catch (Exception e) {
                    String st = e.toString().toLowerCase(Locale.US);
                    if(st.indexOf("address already in use")!=-1){
                        System.out.println("Server ");
                        OK();
                    } else {
                        System.err.println("Erro ao tentar conectar com a port " + port + ": "+ e);
                    }
                    return;
                }
                listen();
            }
        });
        trd.start();
    }

    public void OK(){}//Override

    private void listen(){
        String addressClient = "";
        String portClient = "";
        PrintWriter outServer;

        for (;;) {
            try {
                //Esperando uma conexão (um cliente)
                remote = mySocket.accept();
                System.out.println("remote: "+remote.toString());
                System.out.println("getLocalAddress: "+remote.getLocalAddress().toString());
                System.out.println("getHostName: "+remote.getInetAddress().getHostName().toString());
                System.out.println("getLocalSocketAddress: "+remote.getLocalSocketAddress().toString());
                addressClient = remote.getInetAddress().getHostName().toString();
                portClient = Integer.toString(remote.getLocalPort());
                System.out.println("http://"+addressClient+":"+portClient);

                outServer = new PrintWriter(remote.getOutputStream());

                outServer.println("HTTP/1.0 200 OK");
                outServer.println("Content-type: text/html");
                outServer.println("");
                outServer.println("<html>");
                outServer.println("<body>");
                outServer.println("<p>You address: http://"+addressClient+":"+portClient+"</p>");
                outServer.println("</body>");

                outServer.print("</html>");//last line

                outServer.flush();

                remote.close();
            } catch (Exception e) {
                //System.out.println("loop::Error: " + e);
            }

            try {
                //Thread.currentThread();
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

How to use:

new miniWebServer(8890){
    @Override
    public void OK(){
        System.out.println("OK!");
    }
};

Solution:

Assuming I use the browser GoogleChrome, my java server will return this:

GET /folder/page.html HTTP/1.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US;q=0.6,en;q=0.4
Cache-Control: max-age=0
Connection: keep-alive
Host: localhost:8890
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11

To get the headers and the request: inServer = new BufferedReader(new InputStreamReader(remote.getInputStream()));

then just extract the address of the Host: with .slit(":") or new StringTokenizer(currentLine)

Upvotes: 0

Views: 869

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272307

I think you need to use the complete GET request path as provided by HTTP. The lower level network won't distinguish between whether your client specified a host name or address (since the client itself will map a host name to an address - and what happens if your client is configured with a host / address mapping that your server doesn't have?)

Upvotes: 4

Related Questions