Getting the IP address of the current machine using Java

后端 未结 17 1759
眼角桃花
眼角桃花 2020-11-22 02:26

I am trying to develop a system where there are different nodes that are run on different system or on different ports on the same system.

Now all the nodes create

17条回答
  •  情深已故
    2020-11-22 02:57

    When you are looking for your "local" address, you should note that each machine has not only a single network interface, and each interface could has its own local address. Which means your machine is always owning several "local" addresses.

    Different "local" addresses will be automatically chosen to use when you are connecting to different endpoints. For example, when you connect to google.com, you are using an "outside" local address; but when you connect to your localhost, your local address is always localhost itself, because localhost is just a loopback.

    Below is showing how to find out your local address when you are communicating with google.com:

    Socket socket = new Socket();
    socket.connect(new InetSocketAddress("google.com", 80));
    System.out.println(socket.getLocalAddress());
    

提交回复
热议问题