对如何用Java检索多个IP地址(如果我有多个网卡)有一些疑问? [英] Some doubts about how to retrieve multiple IP addresses (if I have more than one network card) in Java?

查看:120
本文介绍了对如何用Java检索多个IP地址(如果我有多个网卡)有一些疑问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检索客户端的ip时,我遇到以下两个问题.

I have the following 2 problems in retrieving the ip of a client.

我已经在一个类中创建了以下代码:

I have create the following code inside a class:

private static InetAddress thisIp;

static{
    try {
        thisIp  = InetAddress.getLocalHost();
        System.out.println("MyIp is: " + thisIp);
    } catch(UnknownHostException ex) {

    }
}

我的问题是:

1)前面的代码应该检索客户端的IP地址,当我执行它时,它会显示以下消息:

1) The previous code should retrieve the IP address of a client, when I execute it it print the following message:

MyIP是:andrea-virtual-machine/127.0.1.1

为什么以 andrea-virtual-machine/开头? (我正在虚拟机上进行开发),这有问题吗?

Why it begin with andrea-virtual-machine/ ? (I am developing on a virtual machine), is it a problem?

2)这样,我只能检索单个IP地址,但是我可以拥有多个网卡,因此可以拥有多个IP地址,但多个IP地址

2) In this way I can retrieve only a single IP address but I could have more than a single network card so I could have more than a single IP address but multiple IP addresses

我该如何处理这种情况?我想将所有多个IP地址放入ArrayList

What can I do to handle this situation? I want put all the multiple IP addresses into an ArrayList

Tnx

安德里亚

推荐答案

  1. 不,这不是问题,它只是由主机名和IP(hostname/ip)组成的输出.您可能需要阅读的详细信息:实现了类InetAddress中的方法toString()以返回此格式.

  1. No, it's not a problem, it's simply an output that consists of hostname and IP (hostname/ip). A detail that you might want to read up: The method toString() in the class InetAddress is implemented to return this format.

以下代码将列出系统中每个接口的所有IP地址(并将它们存储在列表中,然后您可以继续传递等等):

The following code will list all IP addresses for each of the interfaces in your system (and also stores them in a list that you could then pass on etc...):

public static void main(String[] args) throws InterruptedException, IOException
{
    List<String> allIps = new ArrayList<String>();
    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());
            allIps.add(i.getHostAddress());
        }
    }
}

方法boolean isLoopbackAddress()允许您过滤可能不需要的回送地址.

The method boolean isLoopbackAddress() allows you to filter the potentially unwanted loopback addresses.

返回的InetAddressInet4AddressInet6Address,使用instanceof您可以确定返回的IP是IPv4还是IPv6格式.

The returned InetAddress is either a Inet4Address or a Inet6Address, using the instanceof you can figure out if the returned IP is IPv4 or IPv6 format.

这篇关于对如何用Java检索多个IP地址(如果我有多个网卡)有一些疑问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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