| 1 | |
package com.ctrip.framework.apollo.core.utils; |
| 2 | |
|
| 3 | |
import org.slf4j.Logger; |
| 4 | |
import org.slf4j.LoggerFactory; |
| 5 | |
|
| 6 | |
import java.net.NetworkInterface; |
| 7 | |
import java.nio.BufferUnderflowException; |
| 8 | |
import java.nio.ByteBuffer; |
| 9 | |
import java.security.SecureRandom; |
| 10 | |
import java.util.Enumeration; |
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | 0 | public class MachineUtil { |
| 16 | 0 | private static final Logger logger = LoggerFactory.getLogger(MachineUtil.class); |
| 17 | 0 | private static final int MACHINE_IDENTIFIER = createMachineIdentifier(); |
| 18 | |
|
| 19 | |
public static int getMachineIdentifier() { |
| 20 | 0 | return MACHINE_IDENTIFIER; |
| 21 | |
} |
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
|
| 28 | |
private static int createMachineIdentifier() { |
| 29 | |
|
| 30 | |
int machinePiece; |
| 31 | |
try { |
| 32 | 0 | StringBuilder sb = new StringBuilder(); |
| 33 | 0 | Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); |
| 34 | 0 | while (e.hasMoreElements()) { |
| 35 | 0 | NetworkInterface ni = e.nextElement(); |
| 36 | 0 | sb.append(ni.toString()); |
| 37 | 0 | byte[] mac = ni.getHardwareAddress(); |
| 38 | 0 | if (mac != null) { |
| 39 | 0 | ByteBuffer bb = ByteBuffer.wrap(mac); |
| 40 | |
try { |
| 41 | 0 | sb.append(bb.getChar()); |
| 42 | 0 | sb.append(bb.getChar()); |
| 43 | 0 | sb.append(bb.getChar()); |
| 44 | 0 | } catch (BufferUnderflowException shortHardwareAddressException) { |
| 45 | |
|
| 46 | 0 | } |
| 47 | |
} |
| 48 | 0 | } |
| 49 | 0 | machinePiece = sb.toString().hashCode(); |
| 50 | 0 | } catch (Throwable ex) { |
| 51 | |
|
| 52 | 0 | machinePiece = (new SecureRandom().nextInt()); |
| 53 | 0 | logger.warn( |
| 54 | |
"Failed to get machine identifier from network interface, using random number instead", |
| 55 | |
ex); |
| 56 | 0 | } |
| 57 | 0 | return machinePiece; |
| 58 | |
} |
| 59 | |
} |