客户端java中的服务器地址

时间:2013-02-10 17:26:37

标签: java webserver ip-address hostname

我正在尝试获取客户端访问我服务器的地址。

  • 如果客户端使用http://localhost:8890访问服务器,那么 服务器应准确读取http://localhost:8890

  • 如果客户端使用http://127.0.0.1:8890访问服务器,那么 服务器应准确读取http://127.0.0.1:8890

  • 如果客户端使用http://mywebsite.com:8890访问服务器 然后服务器应该准确读取http://mywebsite.com:8890

我部分地使用了函数[SOCKET].getInetAddress().getHostName()

但是,客户端访问http://127.0.0.1:8890函数[SOCKET].getInetAddress().getHostName()会将其localhost而不是127.0.0.1返回。

我需要服务器获取地址作为发送数据的客户端COOKIES没有丢失任何重定向机会(302 Found301 Moved Permanently)。

我到处搜索,特别是在操作系统中,但我不知道要使用哪些搜索条件(如果有人已经问过这个问题),请原谅我这是否重复。

我的代码:

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();
            }
        }
    }
}

使用方法:

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

解决方案:

假设我使用浏览器GoogleChrome,我的java服务器将返回:

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

获取标题和请求: inServer = new BufferedReader(new InputStreamReader(remote.getInputStream()));

然后只使用Host:.slit(":")

提取new StringTokenizer(currentLine)的地址

1 个答案:

答案 0 :(得分:4)

我认为您需要使用HTTP提供的完整GET请求路径。较低级别的网络不会区分您的客户端是否指定了主机名或地址(因为客户端本身会将主机名映射到某个地址 - 如果您的客户端配置了服务器没有的主机/地址映射会发生什么情况没有?)