程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> java中通過網卡名稱獲取IP地址

java中通過網卡名稱獲取IP地址

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved