Java Network Interface Get getMac()

Here you can find the source of getMac()

Description

get Mac

License

Open Source License

Declaration

public static String getMac() 

Method Source Code

//package com.java2s;
/**//from   ww  w.  j a v a 2s  .  c  o m
 * Tencent is pleased to support the open source community by making APT available.
 * Copyright (C) 2014 THL A29 Limited, a Tencent company. All rights reserved.
 * 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.util.Enumeration;

public class Main {
    private static final String MAC_ADR_NEED_TO_REMOVE = "00000000000000e0";

    public static String getMac() {
        StringBuilder builder = new StringBuilder();
        try {
            Enumeration<NetworkInterface> el = NetworkInterface
                    .getNetworkInterfaces();
            while (el.hasMoreElements()) {
                byte[] mac = el.nextElement().getHardwareAddress();
                StringBuilder subBuilder = new StringBuilder();
                if (mac == null)
                    continue;
                for (byte b : mac) {
                    subBuilder.append(hexByte(b));
                }
                String subMacAdr = subBuilder.toString();
                if (subMacAdr.equalsIgnoreCase(MAC_ADR_NEED_TO_REMOVE)) {
                    continue;
                }
                builder.append(subMacAdr);
            }

            if (builder.length() <= 0) {
                return "-1";
            } else if (builder.length() >= 128) {
                return builder.toString().substring(0, 128);
            } else {
                System.out.println(builder.toString());
                return builder.toString();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return "-1";
        }
    }

    private static String hexByte(byte b) {
        return String.format("%02x", b);
    }
}

Related

  1. getLocalMac()
  2. getLocalNetworkInterface()
  3. getLoopbackInterface()
  4. getLoopbackInterfaceName()
  5. getLoopbackNIF()
  6. getMacBytes()
  7. getNetworkErrorMessage(Throwable e)
  8. getNetworkInterface()
  9. getNetworkInterface()