java根据本地IP获取mac地址的方法
程序员文章站
2023-12-04 14:58:40
本文实例为大家分享了java根据本地ip获取mac地址的具体代码,供大家参考,具体内容如下
import java.net.inetaddress;
imp...
本文实例为大家分享了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 IO流之字符缓冲流实例详解