IP Address not obtained in java

前端 未结 5 1114
北海茫月
北海茫月 2020-12-05 14:26

This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there som

5条回答
  •  春和景丽
    2020-12-05 15:16

    127.0.0.1 is the loopback adapter - it's a perfectly correct response to the (somewhat malfomed) question "what is my IP address?"

    The problem is that there are multiple correct answers to that question.

    EDIT: The docs for getLocalHost say:

    If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned.

    Is it possible that the change in behaviour is due to a change in permissions?

    EDIT: I believe that NetworkInterface.getNetworkInterfaces is what you need to enumerate all the possibilities. Here's an example which doesn't show virtual addresses, but works for "main" interfaces:

    import java.net.*;
    import java.util.*;
    
    public class Test
    {
        public static void main(String[] args)
            throws Exception // Just for simplicity
        {
            for (Enumeration ifaces = 
                   NetworkInterface.getNetworkInterfaces();
                 ifaces.hasMoreElements(); )
            {
                NetworkInterface iface = ifaces.nextElement();
                System.out.println(iface.getName() + ":");
                for (Enumeration addresses =
                       iface.getInetAddresses();
                     addresses.hasMoreElements(); )
                {
                    InetAddress address = addresses.nextElement();
                    System.out.println("  " + address);
                }
            }
        }
    }
    

    (I'd forgotten just how awful the Enumeration type is to work with directly!)

    Here are the results on my laptop right now:

    lo:
      /127.0.0.1
    eth0:
      /169.254.148.66
    eth1:
    eth2:
    ppp0:
      /10.54.251.111
    

    (I don't think that's giving away any hugely sensitive information :)

    If you know which network interface you want to use, call NetworkInterface.getByName(...) and then look at the addresses for that interface (as shown in the code above).

提交回复
热议问题