java根据本地Ip获取mac地址

 1 import java.net.InetAddress;
 2 import java.net.NetworkInterface;
 3 import java.net.SocketException;
 4 import java.net.UnknownHostException;
 5 
 6 public class MacAddress {
 7 
 8     /**
 9      * @param args
10      * @throws UnknownHostException 
11      * @throws SocketException 
12      */
13     public static void main(String[] args) throws UnknownHostException, SocketException {
14 
15         InetAddress ia = InetAddress.getLocalHost();
16         System.out.println(ia);
17         getLocalMac(ia);
18     }
19     private static void getLocalMac(InetAddress ia) throws SocketException {
20         // TODO Auto-generated method stub
21         //获取网卡,获取地址
22         byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
23         
24         System.out.println("mac数组长度:"+mac.length);
25         StringBuffer sb = new StringBuffer("");
26         for(int i=0; i<mac.length; i++) {
27             if(i!=0) {
28                 sb.append("-");
29             }
30             //字节转换为整数
31             int temp = mac[i]&0xff;
32             String str = Integer.toHexString(temp);
33             System.out.println("每8位:"+str);
34             if(str.length()==1) {
35                 sb.append("0"+str);
36             }else {
37                 sb.append(str);
38             }
39         }
40         System.out.println("本机MAC地址:"+sb.toString().toUpperCase());
41     }
42 }

 

下面这个方法是获取客户端请求地址

    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;
    }

 

转载于:https://www.cnblogs.com/huzi007/p/4595787.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值