java ip搜索功能,对如何用Java检索多个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) {

}

}

My problems are:

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

MyIp is: andrea-virtual-machine/127.0.1.1

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

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

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

Tnx

Andrea

解决方案

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.

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 allIps = new ArrayList();

Enumeration e = NetworkInterface.getNetworkInterfaces();

while (e.hasMoreElements())

{

NetworkInterface n = e.nextElement();

System.out.println(n.getName());

Enumeration ee = n.getInetAddresses();

while (ee.hasMoreElements())

{

InetAddress i = ee.nextElement();

System.out.println(i.getHostAddress());

allIps.add(i.getHostAddress());

}

}

}

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值