如何从 Java 中的套接字获取客户端名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5112325/
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
How do I get the client name from a socket in Java?
提问by michael corrigan
Sorry, simple question...but I can't find the answer anywhere using google or in textbooks! I have a simple server, to which a user connects via a socket in java. I want to use this Java socket to retrieve the users client name, is this possible ?
对不起,简单的问题……但我无法在任何地方使用谷歌或教科书找到答案!我有一个简单的服务器,用户通过 java 中的套接字连接到该服务器。我想使用这个 Java 套接字来检索用户的客户端名称,这可能吗?
I know I can use the getInetAddress() method to returns the address to which the socket is connected, but that isn't really what I want. Is there any easy way of doing this ?
我知道我可以使用 getInetAddress() 方法返回套接字连接的地址,但这并不是我真正想要的。有没有简单的方法可以做到这一点?
Thank you.
谢谢你。
回答by Bala R
getInetAddress().getHostName()
EDIT: is your code structured like this?
编辑:您的代码结构是这样的吗?
import java.io.IOException;
import java.net.*;
public class Test {
public void foo() throws IOException{
ServerSocket server = null; //Initialize server socket here.
Socket client = server.accept();
String hostName = client.getInetAddress().getHostName();
}
}