Java 獲得本機的IP與MAC地址完成詳解。本站提示廣大學習愛好者:(Java 獲得本機的IP與MAC地址完成詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Java 獲得本機的IP與MAC地址完成詳解正文
Java 獲得本機的IP與MAC地址
有些機械有很多虛擬的網卡,獲得IP地址時會湧現一些不測,所以須要一些驗證:
// 獲得mac地址
public static String getMacAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
byte[] mac = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
mac = netInterface.getHardwareAddress();
if (mac != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
if (sb.length() > 0) {
return sb.toString();
}
}
}
}
} catch (Exception e) {
_logger.error("MAC地址獲得掉敗", e);
}
return "";
}
// 獲得ip地址
public static String getIpAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
_logger.error("IP地址獲得掉敗", e);
}
return "";
}
以上的代碼中
netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()
能很好地把一些非物理網卡或無用網上過濾失落,然後再取網上的IPV4地址便可。
說到這裡,還有一些經常使用的:
1、獲得以後機械的操作體系
public final static String WIN_OS = "WINDOWS";
public final static String MAC_OS = "MAC";
public final static String LINUX_OS = "LINUX";
public final static String OTHER_OS = "OTHER";
public static String getOS() {
if (SystemUtils.IS_OS_WINDOWS){
return WIN_OS;
}
if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX){
return MAC_OS;
}
if (SystemUtils.IS_OS_UNIX){
return LINUX_OS;
}
return OTHER_OS;
}
2、設置HTTP拜訪署理
/**
* 設置http署理
*/
public static void setHttpProxy() {
Properties prop = System.getProperties();
// 設置http拜訪要應用的署理辦事器的地址
prop.setProperty("http.proxyHost", HTTP_PROXY_HOST);
// 設置http拜訪要應用的署理辦事器的端口
prop.setProperty("http.proxyPort", HTTP_PROXY_PORT);
// 設置不須要經由過程署理辦事器拜訪的主機,可使用*通配符,多個地址用|分隔
prop.setProperty("http.nonProxyHosts", RemoteConfig.PROXT_FILTER_DOMAIN);
}
/**
* 移除http署理
*/
public static void removeHttpProxy() {
Properties prop = System.getProperties();
prop.remove("http.proxyHost");
prop.remove("http.proxyPort");
prop.remove("http.nonProxyHosts");
}
在運用啟動時,拜訪HTTP要求前,設置好就行。固然,http.nonProxyHosts可以不消設置,表現一切的HTTP要求都走署理。
至於HTTPS署理,相似可以如許設置:
System.setProperty("https.proxyHost", "HTTP_PROXY_HOST");
System.setProperty("https.proxyPort", "HTTP_PROXY_PORT");
以上就是Java 獲得本機IP和 MAC的實例,有須要的同伙可以參考下,感謝年夜家對本站的支撐!