Get DNS name of local machine as seen by a remote machine

前端 未结 4 1897
故里飘歌
故里飘歌 2020-12-15 17:59

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 \

相关标签:
4条回答
  • 2020-12-15 18:14

    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();

    0 讨论(0)
  • 2020-12-15 18:21

    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.

    0 讨论(0)
  • 2020-12-15 18:21

    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()

    0 讨论(0)
  • 2020-12-15 18:25

    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.

    0 讨论(0)
提交回复
热议问题