Java InetAddress Create getMacAddress(InetAddress address)

Here you can find the source of getMacAddress(InetAddress address)

Description

Returns the MAC address for the argument IP.

License

Open Source License

Parameter

Parameter Description
address IP address.

Return

MAC address as string.

Declaration

public static String getMacAddress(InetAddress address) 

Method Source Code

//package com.java2s;
/*//  www .  ja  v  a  2  s  .com
Copyright (C) 2011 Bengt Martensson.
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
    
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
    
You should have received a copy of the GNU General Public License along with
this program. If not, see http://www.gnu.org/licenses/.
*/

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

public class Main {
    /**
     * Returns the MAC address for the argument IP.
     * @param address IP address.
     * @return MAC address as string.
     */
    public static String getMacAddress(InetAddress address) {
        try {
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            StringBuilder macAddress = new StringBuilder(32);
            if (ni != null) {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    for (int i = 0; i < mac.length; i++) {
                        macAddress.append(String.format("%02X%s", mac[i], ((i == mac.length - 1) ? "" : "-")));
                    }
                }
            }
            return macAddress.toString();
        } catch (SocketException ex) {
            return null;
        }
    }
}

Related

  1. getLocalInetAddress(String host)
  2. getLocalInetAddresses()
  3. getLocalInetAddresses()
  4. getLocalInetAddresses(boolean includeLoopback)
  5. getMacAddress(InetAddress addr)
  6. getMieleUUIDLowerPart(int deviceType50523, InetAddress address)
  7. getNatType(final InetAddress localAdr, final InetAddress publicAdr)
  8. getNetwork(InetAddress start, InetAddress end)
  9. getNetworkCIDR(InetAddress addr, short prefixLength)