Skip to content

Commit ddbd715

Browse files
committed
create node value from mac address
1 parent 3a61a50 commit ddbd715

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.gb.didgen;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.stereotype.Component;
5+
6+
import java.net.NetworkInterface;
7+
import java.net.SocketException;
8+
import java.security.SecureRandom;
9+
import java.util.Enumeration;
10+
11+
import static com.gb.didgen.common.Constants.NODE_ID_BIT_LEN;
12+
13+
@Component
14+
public class BeanDefinition {
15+
@Bean
16+
public int generatingNodeId() {
17+
int maxNodeVal = (int) Math.pow(2, NODE_ID_BIT_LEN);
18+
int nodeId;
19+
try {
20+
StringBuilder sb = new StringBuilder();
21+
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
22+
while (networkInterfaces.hasMoreElements()) {
23+
NetworkInterface networkInterface = networkInterfaces.nextElement();
24+
byte[] mac = networkInterface.getHardwareAddress();
25+
if (mac != null) {
26+
for (int i = 0; i < mac.length; i++) {
27+
sb.append(String.format("%02X", mac[i]));
28+
}
29+
}
30+
}
31+
nodeId = sb.toString().hashCode();
32+
} catch (SocketException ex) {
33+
//in case of exception get a random number limited by max node size
34+
nodeId = (int) (new SecureRandom().nextInt() % Math.pow(2, 10));
35+
}
36+
nodeId = nodeId & maxNodeVal;
37+
return nodeId;
38+
}
39+
}

0 commit comments

Comments
 (0)