欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-12-17 10:04:54|栏目:JAVA代码|点击:

复制代码 代码如下:

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();
        }
    }
}

上一篇:浅谈Spring中几个PostProcessor的区别与联系

栏    目:JAVA代码

下一篇:idea中Java实体类怎样生成序列化的版本号的方法

本文标题:java中通过网卡名称获取IP地址

本文地址:http://www.codeinn.net/misctech/187176.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有