简体   繁体   English

Java - 从客户端获取服务器的主机名和/或IP地址

[英]Java - Getting a server's hostname and/or ip address from client

So here is my situation. 所以这是我的情况。 I need to use sockets in creating connections between server and client. 我需要使用套接字来创建服务器和客户端之间的连接。 This cannot be negotiated. 这无法协商。 I have a server running and listening using something like this 我有一台服务器在运行和监听使用这样的东西

ServerSocket serverSocket = new ServerSocket(portNumber);
        while (listening) {
            new MultiClientThread(serverSocket.accept()).start();
        }

and I need a client to connect to the "portNumber" being listened to. 我需要一个客户端连接到正在收听的“portNumber”。 The problem is I am using this line of code for the client. 问题是我正在为客户端使用这行代码。

Socket socket = new Socket(hostName, portNumber);

And I do not know how to get the "hostName" part for the parameters. 我不知道如何获得参数的“hostName”部分。 Is it possible to get the "hostName" if I knew the portNumber that was being listened to? 如果我知道正在收听的portNumber,是否可以获取“hostName”? Or maybe another way to word it is how can I connect to a server listening to a port using tcp connections. 或者也许另一种说法是我如何连接到使用tcp连接监听端口的服务器。

hostName usually is hardcoded in the client. hostName通常在客户端中进行硬编码。 It can either be an ip address or a domain name. 它可以是IP地址或域名。 If the server is running the same machine, you can use localhost or 127.0.0.1 as hostname. 如果服务器运行的是同一台计算机,则可以使用localhost127.0.0.1作为主机名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM