Get DNS name of local machine as seen by a remote machine
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 see开发者_C百科ing "You", I want them to see the hostname of their own machine so that User A sees the same text as User B.
See these functions of java.net.InetAddress - getLocalHost and getHostName :
String localhostname = java.net.InetAddress.getLocalHost().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: piskvor@lachtan.my.network.example.com
, instead of just piskvor
.
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.
I've gotten the hostname of the local machine in the past using something like this:
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
You could refer to: InetAddress.getHostName()
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();
精彩评论