View Javadoc

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   * Created by triplem on 24.02.14.
12   */
13  public class NetworkUtils {
14  
15      private static final Logger LOG = Logger.getLogger(NetworkUtils.class);
16  
17      /**
18       * private constructor, this is a utility class
19       */
20      private NetworkUtils() {
21  
22      }
23  
24      /***
25       * Get the MAC Address.
26       *
27       * The previous implementation was kind of "oldschool", see http://www.mkyong.com/java/how-to-get-mac-address-in-java/
28       *
29       * @return
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       * Get the HostName, if any problem attempt to get the MAC Address
59       *
60       * @return
61       */
62      public static String getHostName() {
63          try {
64              InetAddress iAddress = InetAddress.getLocalHost();
65              String hostName = iAddress.getHostName();
66              // String canonicalHostName = iAddress.getCanonicalHostName();
67              return hostName;
68          } catch (Exception e) {
69              LOG.error("Error Getting HostName: ", e);
70          }
71  
72          return getMacAddress();
73      }
74  }