當前位置:首頁 » 編程語言 » java獲取網卡

java獲取網卡

發布時間: 2024-08-08 06:41:12

『壹』 java如何不使用HttpServletRequest獲取電腦客戶端ip地址與Mac地址。

import java.net.InetAddress;
import java.net.NetworkInterface;
/**
*@author:
*@version:
*@description:
*/
public class Ipconfig {
public static void main(String[] args) throws Exception {
try {
InetAddress ia=InetAddress.getLocalHost();
String localname=ia.getHostName();
String localip=ia.getHostAddress();
System.out.println("本機名稱是:"+ localname);
System.out.println("本機的ip是 :"+localip);
System.out.println("MAC ......... "+getMACAddress(ia));
} catch (Exception e) {
e.printStackTrace();
}
}
//獲取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);
sb.append(s.length()==1?0+s:s);
}

//把字元串所有小寫字母改為大寫成為正規的mac地址並返回
return sb.toString().toUpperCase();
}
}

『貳』 java如何查詢本機ip地址和mac地址

Java中可以使用程序來獲取本地ip地址和mac地址,使用InetAddress這個工具類,示例如下:

importjava.net.*;
publicclassNetInfo{
publicstaticvoidmain(String[]args){
newNetInfo().say();
}
publicvoidsay(){
try{
InetAddressi=InetAddress.getLocalHost();
System.out.println(i);//計算機名稱和IP
System.out.println(i.getHostName());//名稱
System.out.println(i.getHostAddress());//只獲得IP
}
catch(Exceptione){e.printStackTrace();}
}
}

也可以通過命令行窗口來查看本地ip和mac地址,輸入命令:ipconfig。

熱點內容
scratch少兒編程課程 發布:2025-04-16 17:11:44 瀏覽:629
榮耀x10從哪裡設置密碼 發布:2025-04-16 17:11:43 瀏覽:357
java從入門到精通視頻 發布:2025-04-16 17:11:43 瀏覽:76
php微信介面教程 發布:2025-04-16 17:07:30 瀏覽:300
android實現陰影 發布:2025-04-16 16:50:08 瀏覽:788
粉筆直播課緩存 發布:2025-04-16 16:31:21 瀏覽:338
機頂盒都有什麼配置 發布:2025-04-16 16:24:37 瀏覽:204
編寫手游反編譯都需要學習什麼 發布:2025-04-16 16:19:36 瀏覽:801
proteus編譯文件位置 發布:2025-04-16 16:18:44 瀏覽:357
土壓縮的本質 發布:2025-04-16 16:13:21 瀏覽:583