Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - How to get the ip address of my computer not the virtual box adapters

In Java I'm trying to get the local machines ip address

String address = InetAddress.getLocalHost().getHostAddress();

and in python I have

socket.gethostbyname(socket.gethostname())

both of these do not return the ip address that I'm looking for. Now I have VirtualBox installed with a couple virtual machines but they aren't on while I run the above 2 lines. Looking at my network connections it shows that I've got a lan adapter for VirtualBox and when I look at the ip that the above code returns and look at the ip for the virtualbox adapter they're the same. Is there any way for me to get my computers local IPv4 Address instead of the other virtual adapter ip's without disabling them?

question from:https://stackoverflow.com/questions/65853946/how-to-get-the-ip-address-of-my-computer-not-the-virtual-box-adapters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A machine can have many IP addresses. The following will enumerate all adapters and show the address(es) for each adapter:

    Enumeration<NetworkInterface> i = NetworkInterface.getNetworkInterfaces();
    while(i.hasMoreElements())
    {
        NetworkInterface n = i.nextElement();
        System.out.println(n.getName());
        Enumeration<InetAddress> ea = n.getInetAddresses();
        while(ea.hasMoreElements())
        {
            InetAddress a = ea.nextElement();
            System.out.println("   "+a.toString());
        }
    }

It's up to you to figure out which adapter(s) and address(es) you're interested in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...