java 获取ipv6地址_获取本机的IPv6地址

废话少说,直接上代码(java)

命令行输出的就是本机的IPv6地址

package app;

import java.net.Inet6Address;

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class IPv6 {

public static void main(String[] args) {

/*获取本机所有ip地址(包括保留地址,ipv4,ipv6 如果安装了虚拟机会更多其他的地址)

* try {

InetAddress ads = null;

Enumeration adds = NetworkInterface.getNetworkInterfaces();

while(adds.hasMoreElements()) {

Enumeration inetAds = adds.nextElement().getInetAddresses();

while(inetAds.hasMoreElements()) {

ads = inetAds.nextElement();

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

}

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}*/

//获取可用ipv6地址

try {

System.out.println(getLocalIPv6Address());

} catch (SocketException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static String getLocalIPv6Address() throws SocketException {

InetAddress inetAddress =null;

Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();

outer:

while(networkInterfaces.hasMoreElements()) {

Enumeration inetAds = networkInterfaces.nextElement().getInetAddresses();

while(inetAds.hasMoreElements()) {

inetAddress = inetAds.nextElement();

//检查此地址是否是IPv6地址以及是否是保留地址

if(inetAddress instanceof Inet6Address&& !isReservedAddr(inetAddress)) {

break outer;

}

}

}

String ipAddr = inetAddress.getHostAddress();

//过滤网卡

int index = ipAddr.indexOf('%');

if(index>0) {

ipAddr = ipAddr.substring(0, index);

}

return ipAddr;

}

private static boolean isReservedAddr(InetAddress inetAddr) {

if(inetAddr.isAnyLocalAddress()||inetAddr.isLinkLocalAddress()||inetAddr.isLoopbackAddress())

{

return true;

}

return false;

}

}

可以使用命令行进行对比

如果是window 输入 ipconfig进行查询

如果是 Linux 输入 ifconfig 进行查询

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值