Mendapatkan Hostname, IP Address, Mac Address dengan Java

| More
Kode berikut membuat kelas NetworkInfo dengan 3 fungsi statis, yaitu hostName, ipAddress, dan macAddress. Ketiga variabel tersebut dapat digunakan untuk mendapatkan Hostname, IP Address, dan Mac Address.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
*
* @author Neutron0690
*/
public final class NetworkInfo {
public final static String ipAddress(){
try {
InetAddress addr = InetAddress.getLocalHost();

// Get IP Address
byte[] ipAddr = addr.getAddress();

// Convert to dot representation
String ipAddrStr = "";
for (int i=0; iif (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i]&0xFF;
}

return ipAddrStr;
} catch (UnknownHostException e) {
return "";
}
}

public final static String hostName(){
try {
InetAddress addr = InetAddress.getLocalHost();

// Get hostname
String hostname = addr.getHostName();

return hostname;
} catch (UnknownHostException e) {
return "";
}
}

public final static String macAddress(){
try {
InetAddress address = InetAddress.getLocalHost();

/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();

/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
String tmp = "";
for (int i = 0; i < tmp =" tmp" class="character">"%02X%s", mac[i], (i < class="character">"-" : "");
}

return tmp;
} catch (UnknownHostException e) {
e.printStackTrace();
return "";
} catch (SocketException e) {
e.printStackTrace();
return "";
}
}
}


Contoh cara pemanggilannya dapat secara langsung karena bersifat statis:
System.out.println(" Hostname = " + NetworkInfo.hostName());
System.out.println(" IPAddress = " + NetworkInfo.ipAddress());
System.out.println(" MacAddress = " + NetworkInfo.macAddress());

4 komentar

Make A Comment
top