Here you can find the source of getMacAddrs()
Parameter | Description |
---|---|
SocketException | if an I/O error occurs. |
null
if the address doesn't exist or is not accessible.
public static String[] getMacAddrs() throws SocketException
//package com.java2s; /*//from w w w. j av a 2 s .com * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class Main { /** * Hex array */ private final static char[] HEXARRAY = "0123456789ABCDEF".toCharArray(); /** * Returns the hardware address (usually MAC) of the interface if it * has one and if it can be accessed given the current privileges. * * @return a char array containing the first address or <code>null</code> if * the address doesn't exist or is not accessible. * @throws SocketException if an I/O error occurs. * @since 1.6 */ public static String[] getMacAddrs() throws SocketException { Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); StringBuilder buf = new StringBuilder(); while (e.hasMoreElements()) { NetworkInterface network = e.nextElement(); if (network != null) { byte[] nmac = network.getHardwareAddress(); if (nmac != null) { buf.append(hexdump(nmac)); buf.append("#"); } } } return buf.toString().split("#"); } /** * Format bytes to hex byte * * @param bytes bytes * @return hex string */ public static String hexdump(final byte[] bytes) { if (bytes == null || bytes.length < 1) return "[no data]"; int length = bytes.length; int temp; char[] hex = new char[length * 2]; for (int i = 0; i < length; i++) { // UnsignedByte temp = bytes[i] & 0xFF; hex[i * 2] = HEXARRAY[temp >>> 4]; hex[i * 2 + 1] = HEXARRAY[temp & 0x0F]; } return new String(hex); } }