通过网卡名称获取IP java中通过网卡名称获取IP地址

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

通过网卡名称获取IP java中通过网卡名称获取IP地址

  2021-03-18 我要评论
想了解java中通过网卡名称获取IP地址的相关内容吗,在本文为您仔细讲解通过网卡名称获取IP的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:网卡,IP,下面大家一起来学习吧。

复制代码 代码如下:

package me.xuzs.sso.test;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class InternetTest {

    public static void main(String[] args) {
        String netCard = "lo";
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            if (netInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = netInterfaces.nextElement();
                if (netCard.equals(netInterface.getName())) {
                    // 子接口,linux下会取到父接口??
                    Enumeration<NetworkInterface> subnetInterfaces = netInterface
                            .getSubInterfaces();
                    while (subnetInterfaces.hasMoreElements()) {
                        NetworkInterface subnetInterface = subnetInterfaces
                                .nextElement();
                        System.out.println(subnetInterface.getName());
                        Enumeration<InetAddress> subaddresses = netInterface
                                .getInetAddresses();
                        while (subaddresses.hasMoreElements()) {
                            InetAddress subaddress = subaddresses.nextElement();
                            System.out.println(subaddress.getHostAddress());
                        }
                    }
                    // 打印接口下所有IP
                    System.out.println(netInterface.getName());
                    Enumeration<InetAddress> addresses = netInterface
                            .getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        System.out.println(address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们