获取服务器mac地址,通过拦截器拦截请求,校验mac地址,完成!
代码:
一、获取mac地址工具类:
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
@Slf4j
public class MacAddressUtil {
/**
* 获取银河麒麟mac地址
* @return
* @throws SocketException
*/
public static String getMACAddressByKylin() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()) {
NetworkInterface network = networkInterfaces.nextElement();
//log.info("银河麒麟 network:{}", network);
byte[] mac = network.getHardwareAddress();
if(mac == null) {
log.warn("mac is null");
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
log.info("银河麒麟 MAC address : {} ", sb);
if (!"".equals(sb.toString())) {
return sb.toString();
}
break;
}
}
return "";
}
/**
* 获取linux系统mac地址
* @return
*/
public static String getMacAddressByLinux(){
List<String> macs = new ArrayList<>();
BufferedReader bufferedReader = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("ifconfig -a");
bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("硬件地址");
String mac = "";
if (index != -1) {
mac = line.substring(index + 4).trim();
macs.add(mac.toLowerCase());
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}
log.info("Linux:"+macs);
return macs.toString();
}
/**
* 获取windows系统mac地址
* @return
* @throws Exception
*/
public static List<String> getMACAddressByWindows() throws Exception {
ArrayList<String> rs = new ArrayList<>();
String result = "";
Process process = Runtime.getRuntime().exec("ipconfig /all");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
int index = -1;
String line;
while ((line = br.readLine()) != null) {
index = line.indexOf("物理地址");
if (index >= 0) {
index = line.indexOf(":");
if (index >= 0) {
result = line.substring(index + 1).trim();
}
rs.add(result.toUpperCase());
}
}
br.close();
log.info("windows Mac address : {}",rs);
return rs;
}
/**
* 获取uso系统mac地址
* @return
*/
public static List<String> getMacAddressByUSO() {
ArrayList<String> macs = new ArrayList<>();
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
byte[] mac = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint() || !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) {
macs.add(sb.toString().toLowerCase());
}
}
}
}
log.info("UOS 获取的mac地址为:{}", macs);
return macs;
} catch (Exception e) {
log.error("UOS MAC地址获取失败", e);
}
return Collections.emptyList();
}
}
二、通过控制器获取mac地址,在部署前修改项目的yml配置文件,或者添加到数据库,这个看个人习惯
控制器:
@RestController
@RequestMapping("/mac")
public class SysMacController {
@Autowired
private ISysMacService sysMacService;
/**
* 查询银河麒麟系统mac地址
* @return
*/
@GetMapping("/ql")
public String getMAC(){
String mac = null;
try {
mac = MacAddressUtil.getMACAddressByKylin();
} catch (SocketException e) {
e.printStackTrace();
}
return mac;
}
/**
* 查询linux系统mac地址
* @return
*/
@GetMapping("/linux")
public String getLinuxMac(){
String linuxMac = MacAddressUtil.getMacAddressByLinux();
return linuxMac;
}
/**
* 查询windows系统mac地址
* @return
*/
@GetMapping("/win")
public List<String> getMACAddressByWindows() throws Exception {
return MacAddressUtil.getMACAddressByWindows();
}
/**
* 查询USO系统mac地址
* @return
*/
@GetMapping("/uso")
public List<String> getMacAddress() {
return MacAddressUtil.getMacAddressByUSO();
}
@PostMapping("/add")
public Integer addMac(String macAddress){
SysMac sysMac = new SysMac();
sysMac.setMacAddress(macAddress);
return sysMacService.insertSysMac(sysMac);
}
@GetMapping("/get")
public List<SysMac> getMac(SysMac mac){
List<SysMac> sysMacs = sysMacService.selectSysMacList(mac);
return sysMacs;
}
}
yml
#Mac地址
mac:
address: 88-53-95-2B-76-37
三、拦截器,每次请求都拦截(也可以放行)
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor())
//放行
.excludePathPatterns("/mac/ql")
//拦截
.addPathPatterns("/mac/**");
}
}
@Slf4j
@Component
public class MacAddressInterceptor implements HandlerInterceptor {
@Value("${mac.address}")
private String macAddress;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String macAddressByKylin = MacAddressUtil.getMACAddressByKylin();
if (macAddress.equals(macAddressByKylin)) {
log.info("mac地址验证通过!");
return true;
}
log.info("mac地址验证未通过!拦截!!!");
return false;
}
}
ps:此处有个小坑,@Value获取不到yml配置文件的值,可以参考大佬的文档!!!
很简单的一个小功能。
完成!