获取远程计算机看到的本地计算机的 DNS 名称
我正在制作一个点对点即时消息应用程序。
目前,如果 UserA.pool.net 对 UserB.pool.net 说“hello”,则用户 A 会看到“You: hello”,用户 B 会看到“UserA.pool.net: hello”。
我希望用户 A 看到自己计算机的主机名,而不是看到“您”,以便用户 A 看到与用户 B 相同的文本。
I'm making a peer-to-peer instant messaging application.
Currently, if UserA.pool.net says "hello" to UserB.pool.net, User A sees "You: hello" and User B sees "UserA.pool.net: hello".
Rather than User A seeing "You", I want them to see the hostname of their own machine so that User A sees the same text as User B.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅 java.net.InetAddress 的这些函数 - getLocalHost 和 getHostName< /a> :
请注意,这会获取机器看到的主机名;其他人可能会看到它与不同的文件(例如本地
hosts
文件显示与 DNS 不同的内容)。换句话说,不能保证机器 A 会被机器 A、机器 B 或机器 C 看到具有相同的主机名。正如 @biniam_Ethiopia 指出的,甚至不能保证您会从不同的主机获得相同的结果。同一台计算机上的程序,因为它们可能使用基于网络的名称解析(参见例如 此处)。
发送整个标识符可能更有用:
[电子邮件受保护]
,而不仅仅是piskvor
。See these functions of java.net.InetAddress - getLocalHost and getHostName :
Note that this gets you the hostname as the machine sees itself; others may see it with a different one (e.g. the local
hosts
file says something different than DNS). In other words, it is not guaranteed that machine A will be seen with the same hostname from machine A, machine B, or machine C.As @biniam_Ethiopia points out, it is not even guaranteed that you'll get the same result from different programs on the same machine, as they may be using network-based name resolution (seen e.g. here).
It may be more useful to send the whole identifier:
[email protected]
, instead of justpiskvor
.简而言之,如果您确实希望用户 A 和用户 B 看到相同的文本,则不能依赖自己查找主机名。您需要用户 B 将其对用户 A 主机名的视图传输给用户 A,反之亦然。由于 NAT,您将无法仅检查自己计算机的主机名。
或者,(乔纳森在问题评论中击败了我)您可以让每个用户发送自己的私有主机名作为连接握手的一部分,并使用它在远程端打印消息。
The short answer is that if you really want User A and User B to see the same text, you can't rely on finding out your hostname yourself. You need User B to transmit their view of User A's hostname to User A and vice versa. Due to NAT, you won't be able to just check your own computer's hostname.
Alternatively, (Jonathon beat me to this in the question comments) you can have each user send their own private hostname as part of the connection handshake and use that to print messages on the remote end.
我过去使用类似这样的方法获取了本地计算机的主机名:
您可以参考: InetAddress.getHostName()
I've gotten the hostname of the local machine in the past using something like this:
You could refer to: InetAddress.getHostName()
您可能需要使用 getCanonicalHostName() 来获取完整的合格主机名,其中还包括域名。
代码 -
String fullHostName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
You may need to use getCanonicalHostName() to get full qualified host name which include domain name also.
Code -
String fullHostName = java.net.InetAddress.getLocalHost().getCanonicalHostName();