개발중/Spring
Java: MAC Address 조회하기 예제
Binsoo
2024. 12. 10. 10:16
728x90
반응형
IP 구하는 메서드 구현
public static String getIpAddress(HttpServletRequest request) {
String ipAddress = "";
try{
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
return ipAddress = request.getRemoteAddr();
}
}catch (Exception e){
e.printStackTrace();
}finally {
return ipAddress;
}
}
MAC 주소 구하는 메서드 구현
public static String getMacAddress(String ipAddress) {
String macAddress = "-";
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress);
if (network == null || network.isLoopback()) {
// 로컬 머신의 기본 네트워크 인터페이스를 가져옴
network = NetworkInterface.getNetworkInterfaces()
.asIterator()
.next(); // 첫 번째 네트워크 인터페이스 사용
}
if (network != null) {
byte[] mac = network.getHardwareAddress();
if (mac != null) {
StringBuilder macBuilder = new StringBuilder();
for (byte b : mac) {
macBuilder.append(String.format("%02X:", b));
}
macAddress = macBuilder.substring(0, macBuilder.length() - 1); // 마지막 콜론 제거
}
}
} catch (Exception e) {
e.printStackTrace();
}
return macAddress;
}
HttpServletRequest 로 ip 를 구하고 ip 를 활용해서 mac 주소를 구한다.
String ipAddress = NetworkInfo.getIpAddress(request);
String macAddress = NetworkInfo.getMacAddress(ipAddress);
728x90
반응형