Java:在我的家庭网络中获得我自己的IP地址 [英] Java: Get my own ip address in my home network

查看:111
本文介绍了Java:在我的家庭网络中获得我自己的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到两个示例,以获取路由器给我的PC的IP地址. 这是代码:

I have find two examples on the web to get the ip address the router has given to my pc. Here is the code:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class tryNet {

public static void displayStuff(String whichHost, InetAddress inetAddr) {
    System.out.println("---------------------");
    System.out.println("host: " + whichHost);
    System.out.println("Canonical host name: " + inetAddr.getCanonicalHostName());
    System.out.println("Host Name: " + inetAddr.getHostName());
    System.out.println("Host Address: " + inetAddr.getHostAddress());
    System.out.println("---------------------");
}


public static void main(String argv[]) {
    try {
        InetAddress inetAddr = InetAddress.getLocalHost();
        displayStuff("localhost", inetAddr);
    }

    catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

}

我已经阅读了初始化后的内容 InetAddress inetAddr = InetAddress.getLocalHost(); 我可以用这个方法 inetAddr.getHostAddress() 获取我的路由器提供的IP地址(例如在ubuntu的终端中写入ifconfig或在Windows中的ipconfig) 相反,它返回了我的回送地址...(127.0.0.1) 为什么?

I have read that after having initialized InetAddress inetAddr = InetAddress.getLocalHost(); I can use the method inetAddr.getHostAddress() to get my ip address, the one given by my router (such as write ifconfig in the terminal in ubuntu, or ipconfig in windows) Instead it returns me my loopback address...(127.0.0.1) Why?

推荐答案

您的PC具有多个接口(至少两个)和多个IP地址(当然,如果已插入网络).通常,localhost将解析为127.0.0.1(在回送接口上),并且您正在使用的各种方法将返回该值.

Your PC has multiple interfaces (at least two) and multiple IP addresses (If it's plugged into a network, of course). Typically localhost is going to resolve to 127.0.0.1 (on the loopback interface) and the various methods you are using are going to return that.

以下内容将向您显示计算机上的所有接口以及分配给它们的IP地址:

The following will show you all the interfaces on the machine and the IP addresses assigned to them:

public static void main(String[] args) throws InterruptedException, IOException
{
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements())
    {
        NetworkInterface n = e.nextElement();
        System.out.println(n.getName());
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements())
        {
            InetAddress i = ee.nextElement();
            System.out.println(i.getHostAddress());
        }
    }
}

这篇关于Java:在我的家庭网络中获得我自己的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆