Java - 从客户端获取服务器的主机名和/或 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20020604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Getting a server's hostname and/or ip address from client
提问by Javier Pena
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. 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. Is it possible to get the "hostName" if I knew the portNumber that was being listened to? Or maybe another way to word it is how can I connect to a server listening to a port using tcp connections.
而且我不知道如何获取参数的“hostName”部分。如果我知道正在侦听的端口号,是否可以获得“主机名”?或者也许另一种说法是如何连接到使用 tcp 连接侦听端口的服务器。
采纳答案by Femaref
hostName
usually is hardcoded in the client. It can either be an ip address or a domain name. If the server is running the same machine, you can use localhost
or 127.0.0.1
as hostname.
hostName
通常在客户端硬编码。它可以是IP地址或域名。如果服务器运行在同一台机器上,您可以使用localhost
或127.0.0.1
作为主机名。