欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-13 13:22:10
复制代码 代码如下:package me.xuzs.sso.test; import java.net.inetaddress;import java.net.netwo...

复制代码 代码如下:

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

上一篇:

下一篇: