標籤:content amp col not cal ipv4 get imp 代碼
java擷取本機名稱、IP、MAC地址和網卡名稱
摘自:80364370
2018年05月18日 14:53:19閱讀數:134
- import java.net.InetAddress;
- import java.net.NetworkInterface;
-
- public class IpConfig {
- @SuppressWarnings("static-access")
- public static void main(String[] args) throws Exception {
- InetAddress ia = null;
- try {
- ia = ia.getLocalHost();
- String localname = ia.getHostName();
- String localip = ia.getHostAddress();
- System.out.println("本機名稱是:" + localname);
- System.out.println("原生ip是 :" + localip);
- } catch (Exception e) {
- e.printStackTrace();
- }
- InetAddress ia1 = InetAddress.getLocalHost();// 擷取本地IP對象
- System.out.println("原生MAC是 :" + getMACAddress(ia1));
- }
-
- // 擷取MAC地址的方法
- private static String getMACAddress(InetAddress ia) throws Exception {
- // 獲得網路介面對象(即網卡),並得到mac地址,mac地址存在於一個byte數組中。
- byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
- // 下面代碼是把mac地址拼裝成String
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < mac.length; i++) {
- if (i != 0) {
- sb.append("-");
- }
- // mac[i] & 0xFF 是為了把byte轉化為正整數
- String s = Integer.toHexString(mac[i] & 0xFF);
- // System.out.println("--------------");
- // System.err.println(s);
- sb.append(s.length() == 1 ? 0 + s : s);
- }
- // 把字串所有小寫字母改為大寫成為正規的mac地址並返回
- return sb.toString().toUpperCase();
- }
- }
輸出結果如下:
本機名稱是:PC-DaiHaijiao
原生ip是 :172.16.0.31
原生MAC是 :00-FF-0D-99-5E-1E
- import java.net.Inet4Address;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.util.Enumeration;
-
- public class NetworkInterfaceTest {
-
- public static void main(String[] args) throws Exception {
- // 獲得原生所有網路介面
- Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
- while (nifs.hasMoreElements()) {
- NetworkInterface nif = nifs.nextElement();
- // 獲得與該網路介面綁定的 IP 位址,一般只有一個
- Enumeration<InetAddress> addresses = nif.getInetAddresses();
- while (addresses.hasMoreElements()) {
- InetAddress addr = addresses.nextElement();
- if (addr instanceof Inet4Address) { // 只關心 IPv4 地址
- System.out.println("網卡介面名稱:" + nif.getName());
- System.out.println("網卡介面地址:" + addr.getHostAddress());
- System.out.println();
- }
- }
- }
- }
- }
輸出結果如下:
網卡介面名稱:lo
網卡介面地址:127.0.0.1
網卡介面名稱:eth0
網卡介面地址:172.16.0.31
網卡介面名稱:eth2
網卡介面地址:192.168.220.1
網卡介面名稱:wlan2
網卡介面地址:192.168.0.108
網卡介面名稱:eth8
網卡介面地址:192.168.138.1
java擷取本機名稱、IP、MAC地址和網卡名稱