java根据本地IP获取mac地址的方法
时间:2020-10-22 22:16:30|栏目:JAVA代码|点击: 次
本文实例为大家分享了java根据本地IP获取mac地址的具体代码,供大家参考,具体内容如下
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; public class MacAddress { /** * @param args * @throws UnknownHostException * @throws SocketException */ public static void main(String[] args) throws UnknownHostException, SocketException { InetAddress ia = InetAddress.getLocalHost(); System.out.println(ia); getLocalMac(ia); } private static void getLocalMac(InetAddress ia) throws SocketException { // TODO Auto-generated method stub //获取网卡,获取地址 byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); System.out.println("mac数组长度:"+mac.length); StringBuffer sb = new StringBuffer(""); for(int i=0; i<mac.length; i++) { if(i!=0) { sb.append("-"); } //字节转换为整数 int temp = mac[i]&0xff; String str = Integer.toHexString(temp); System.out.println("每8位:"+str); if(str.length()==1) { sb.append("0"+str); }else { sb.append(str); } } System.out.println("本机MAC地址:"+sb.toString().toUpperCase()); } }
下面这个方法是获取客户端请求地址
public String getClientIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if(ip.trim().contains(",")){ String [] ips=ip.split(","); ip=ips[0]; } return ip; }
上一篇:Java使用自动化部署工具Gradle中的任务设定教程
栏 目:JAVA代码
本文标题:java根据本地IP获取mac地址的方法
本文地址:http://www.codeinn.net/misctech/14550.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机