Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

public class Main {
    /**
     * Generate a unicast MAC address.
     * A unicast MAC address is the one with an even second hex.
     * i.e. x[0,2,4,6,8,A,C,E]:xx:xx:xx:xx:xx
     * 
     * @return Unicast MAC address
     */
    public static String generateRandomMACAddress() {
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        sb.append(Integer.toHexString(r.nextInt(16)));
        int i = r.nextInt(16);
        while (i % 2 != 0)
            i = r.nextInt(16);
        sb.append(Integer.toHexString(i));
        while (sb.length() <= 12)
            sb.append(Integer.toHexString(r.nextInt()));
        String address = prepareMACAddress(sb.subSequence(0, 12).toString());
        if (address.equals("ff:ff:ff:ff:ff:ff"))
            return generateRandomMACAddress();
        return address;
    }

    /**
     * format a string as a MAC address
     * 
     * @param address
     *            String containing at least 12 hexadecimal values
     * @return well formed MAC address
     */
    public static String prepareMACAddress(String str) {
        String address = str.replaceAll("[^a-fA-F0-9]", "").toLowerCase();
        if (address.length() < 12)
            return null;
        String[] marr = address.split("");
        address = "";
        int i;
        for (i = 1; i < 10; i = i + 2)
            address += marr[i] + marr[i + 1] + ":";
        address += marr[i] + marr[i + 1];
        return address;
    }
}