All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ibankapp.base.system.NetCard Maven / Gradle / Ivy

There is a newer version: 1.0.0-beta.6
Show newest version
/*
 * iBankApp
 *
 * License : Apache License,Version 2.0, January 2004
 *
 * See the LICENSE file in English or LICENSE.zh_CN in chinese
 * in the root directory or .
 */

package org.ibankapp.base.system;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 与网卡相关的工具类
 *
 * @author ibankapp
 * @author esailor
 * @since 1.0.0
 */
public class NetCard {


  /**
   * 获取机器上所有网卡的InetAddress信息.
   *
   * @return 所有网卡的InetAddress信息列表
   * @throws SocketException 获取网卡列表信息异常时抛出
   */
  public static List getCardsInfo() throws SocketException {

    Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
    List addressList = new ArrayList();
    while (interfaces.hasMoreElements()) {
      NetworkInterface ni = interfaces.nextElement();
      Enumeration address = ni.getInetAddresses();

      while (address.hasMoreElements()) {
        InetAddress ia = address.nextElement();

        addressList.add(ia);
      }
    }
    return addressList;
  }


  /**
   * 获取Set类型的MAC地址集合.
   *
   * @return 网卡mac地址的set集合
   * @throws SocketException 调用getCardsInfo()和获取mac地址时异常时抛出
   */
  public static Set getMacAddresses() throws SocketException {
    Set set = new HashSet();
    List ias = getCardsInfo();
    for (InetAddress ia : ias) {
      byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
      if (mac == null) {
        continue;
      }
      StringBuilder sb = new StringBuilder("");
      for (int i = 0; i < mac.length; i++) {
        if (i != 0) {
          sb.append(":");
        }
        int temp = mac[i] & 0xff;
        String str = Integer.toHexString(temp);
        if (str.length() == 1) {
          sb.append("0").append(str);
        } else {
          sb.append(str);
        }
      }
      set.add(sb.toString());
    }
    return set;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy