NetUtils.java 1.46 KB
package com.bs.fileservice.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class NetUtils {

    public static Long getLocalNodeId() {
        InetAddress address = localInetAddress();
        if (address == null) {
            return null;
        } else {
            byte[] ipAddressByteArray = address.getAddress();
            long node1 = (long) ((ipAddressByteArray[ipAddressByteArray.length - 2] & 3) << 8);
            long node2 = (long) (ipAddressByteArray[ipAddressByteArray.length - 1] & 255);
            Long nodeValue = node1 + node2;
            return nodeValue;
        }
    }

    private static InetAddress localInetAddress() {
        InetAddress address = null;

        try {
            address = InetAddress.getByName(getSelfIP());
            return address;
        } catch (UnknownHostException var2) {
            throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!", var2);
        }
    }

    public static String getSelfIP() {
        InetAddress inetAddress = null;

        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException var3) {
            var3.printStackTrace();
        }

        String tmpSelfIP = inetAddress.getHostName();
        String tmpSelfIP2 = inetAddress.getCanonicalHostName();
        System.out.println("IP:" + tmpSelfIP);
        System.out.println("IPTO:" + tmpSelfIP2);
        return tmpSelfIP;
    }

}