1 package org.rpi.utils;
2
3 import org.apache.log4j.Logger;
4
5 import java.net.InetAddress;
6 import java.net.NetworkInterface;
7 import java.net.SocketException;
8 import java.net.UnknownHostException;
9
10
11
12
13 public class NetworkUtils {
14
15 private static final Logger LOG = Logger.getLogger(NetworkUtils.class);
16
17
18
19
20 private NetworkUtils() {
21
22 }
23
24
25
26
27
28
29
30
31 public static String getMacAddress() {
32 InetAddress ip;
33
34 StringBuilder sb = new StringBuilder();
35
36 try {
37 ip = InetAddress.getLocalHost();
38 NetworkInterface network = NetworkInterface.getByInetAddress(ip);
39
40 byte[] mac = network.getHardwareAddress();
41
42 for (int i = 0; i < mac.length; i++) {
43 sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
44 }
45
46 }
47 catch (UnknownHostException uhex) {
48 LOG.error(uhex);
49 }
50 catch (SocketException sex) {
51 LOG.error(sex);
52 }
53
54 return sb.toString();
55 }
56
57
58
59
60
61
62 public static String getHostName() {
63 try {
64 InetAddress iAddress = InetAddress.getLocalHost();
65 String hostName = iAddress.getHostName();
66
67 return hostName;
68 } catch (Exception e) {
69 LOG.error("Error Getting HostName: ", e);
70 }
71
72 return getMacAddress();
73 }
74 }