package com.engine.common.util.genid;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Random;

public class DefaultWorker implements Worker{
    private Random random = new Random();

    public DefaultWorker() {
    }

    public long getWorkerId() {
        int max = 100000;
        int min = 10000;
        int s = this.random.nextInt(max) % (max - min + 1) + min;
        String ip = this.getHostIp();
        long workerId = 0L;
        if (ip != null) {
            String str = ip.replaceAll("\\.", "") + s;
            workerId = Long.parseLong(str);
            workerId %= 1024L;
        }

        return workerId;
    }

    private String getHostIp() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();

            while(allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface)allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();

                while(addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress)addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return "127.0.0.1";
    }
}
