Java Local Host Get createLocalHostID(int size)

Here you can find the source of createLocalHostID(int size)

Description

Generates a byte array of the given size that should be a value unique to the host on which the current Java virtual machine is running.

License

Apache License

Parameter

Parameter Description
size Number of bytes or host id required. Values of 6 and 8 are recommended as the only values likely to produce reasonably reliable results.

Exception

Parameter Description
NegativeArraySizeException Cannot create a unique host ID value with a negative array size.

Return

An array of bytes extracted from some relatively unique properties of the current system. Using this function on a set of systems on a network controlled by one organisation should produce unique results for each different system.

Declaration

public final static byte[] createLocalHostID(int size) throws NegativeArraySizeException 

Method Source Code


//package com.java2s;
/*/*from www.  j  a va  2 s  .  c  o  m*/
 * Copyright 2016 Richard Cartwright
 *
 * 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.InetAddress;

import java.net.UnknownHostException;

public class Main {
    /**
     * <p>Generates a byte array of the given size that should be a value unique to the host
     * on which the current Java virtual machine is running. Java does not have an API call to 
     * access the unique hardware address of a system, so bytes compatible with an
     * <a href="http://en.wikipedia.org/wiki/MAC_Address">EUI-48 or EUI-64</a>
     * <em>locally administered</em> value is generated.</p>
     * 
     * <p>The four most significant bytes of the generated host id are set to be the four most 
     * significant bytes of the IP address of the current system. The least significant bits of
     * the value are taken from the most local part of the domain name for the system. This is done
     * with the intention that locally administered systems on separate private networks within 
     * different organisation should generate different ids.</p>
     * 
     * <p>If no local network information is available, other local information about the identification
     * of the machine is used instead. Note that this technique is likely to generate very similar
     * or clashing host ids for systems configured with the same operating system, Java virtual machine
     * and username.</p>
     * 
     * <p>This method is no substitute for administering local system identities directly or using
     * actual MAC addresses. The method should provide some degree of host id uniqueness within 
     * an organisation but should be used with caution if used as part of a public system or 
     * business-to-business applications. A much better approach is to pass the MAC address of
     * a system in to a Java virtual machine as a system property, including a unique virtual machine id
     * if the same system will be running more than one instance of an operating system in parallel.</p>
     *
     * @param size Number of bytes or host id required. Values of&nbsp;6 and&nbsp;8 are recommended as the only
     * values likely to produce reasonably reliable results.
     * @return An array of bytes extracted from some relatively unique properties of the current
     * system. Using this function on a set of systems on a network controlled by one organisation
     * should produce unique results for each different system. 
     * 
     * @throws NegativeArraySizeException Cannot create a unique host ID value with a negative array size.
     * 
     * @see tv.amwa.maj.industry.Forge#setLocalNodeID(byte[])
     * @see tv.amwa.maj.industry.Forge#timebasedAUID()
     * @see tv.amwa.maj.industry.Forge#generatePackageID(tv.amwa.maj.enumeration.MaterialType, tv.amwa.maj.record.InstanceNumberGeneration, tv.amwa.maj.record.MaterialNumberGeneration)
     * @see #getLocalHostID()
     */
    public final static byte[] createLocalHostID(int size) throws NegativeArraySizeException {

        if (size < 0)
            throw new NegativeArraySizeException(
                    "Cannot create a unique host ID value with a negative array size.");

        byte[] hostAddress = null;
        String hostname = null;
        try {
            InetAddress hostInetAddress = java.net.InetAddress.getLocalHost();
            hostAddress = hostInetAddress.getAddress();
            hostname = hostInetAddress.getCanonicalHostName();
        } catch (UnknownHostException uhe) {
            hostAddress = new byte[] { System.getProperty("os.version").getBytes()[0],
                    System.getProperty("os.arch").getBytes()[0], System.getProperty("os.name").getBytes()[0],
                    System.getProperty("java.vm.name").getBytes()[0] };
            hostname = System.getProperty("user.dir");
        }

        byte[] hostID = new byte[8];

        // Try to extract the most local part of the domain name
        int firstDot = hostname.indexOf('.');
        if ((firstDot == -1) || (firstDot >= hostname.length() - 4)) {
            hostID[0] = (byte) 'x';
            hostID[1] = (byte) 'x';
            hostID[2] = (byte) 'x';
            hostID[4] = (byte) 'x';
        } else {
            byte[] endOfTheDomain = hostname.substring(firstDot + 1, firstDot + 5).getBytes();
            System.arraycopy(endOfTheDomain, 0, hostID, 0, 4);
        }

        System.arraycopy(hostAddress, hostAddress.length - 4, hostID, 4, 4);

        // Set the locally administered flag (7th bit of the first byte is 1) and unicast (8th bit of
        // the first byte is 0).
        hostID[0] = (byte) ((((int) hostID[0]) & 0xfc) | 2);

        switch (size) {

        case 6:
            byte[] shorter = new byte[6];
            shorter[0] = hostID[0];
            System.arraycopy(hostID, 3, shorter, 1, 5);
            return shorter;
        case 8:
            return hostID;
        default:
            return checkBytes(hostID, size);
        }
    }

    /**
     * <p>Ensures that an array contains exactly the required number of bytes. If it does not, 
     * it is either padded with 0s to the right to make it up to the required length or truncated
     * at the required length to make it fit.</p>
     * 
     * <p>If the array passed in is <code>null</code>, an array of the required length containing 0's
     * is created.</p>
     * 
     * @param data Array to check the length of.
     * @param requiredLength Required length of the array.
     * @return If the length is OK, a cloned copy of the given array. Otherwise, a replacement array 
     * is created that is a padded or truncated version of the one provided to the required length.
     * 
     * @throws NegativeArraySizeException The required array length is negative, which is not
     * allowed for an array length. 
     * 
     * @see tv.amwa.maj.record.PackageID
      * @see tv.amwa.maj.record.AUID
     */
    public static final byte[] checkBytes(byte[] data, int requiredLength) throws NegativeArraySizeException {

        if (data == null)
            data = new byte[0];

        if (data.length != requiredLength) {

            byte[] replacement = new byte[requiredLength];
            for (int u = 0; u < requiredLength; u++)
                replacement[u] = (byte) 0;

            if (data.length < requiredLength) {
                for (int u = 0; u < data.length; u++)
                    replacement[u] = data[u];
            } else {
                for (int u = 0; u < requiredLength; u++)
                    replacement[u] = data[u];
            }
            return replacement;
        }

        return data.clone();
    }
}

Related

  1. getAllLocalHostNames()
  2. getCanonicalLocalHostName()
  3. getCanonicalLocalHostName()
  4. getLocalHost()