Java web 怎么得到客户端的 Mac 地址

Python020

Java web 怎么得到客户端的 Mac 地址,第1张

import java.net.InetAddress

import java.net.NetworkInterface

import java.net.SocketException

import java.net.UnknownHostException

/*

* 物理地址是48位,别和ipv6搞错了

*/

public class LOCALMAC {

/**

* @param args

* @throws UnknownHostException

* @throws SocketException

*/

public static void main(String[] args) throws UnknownHostException, SocketException {

// TODO Auto-generated method stub

//得到IP,输出PC-201309011313/122.206.73.83

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=0i<mac.lengthi++) {

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())

}

}

/**

* 获取IP地址

* @return

*/

public static String GetNetIp() {

URL infoUrl = null

InputStream inStream = null

String line = ""

try {

infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8")

URLConnection connection = infoUrl.openConnection()

HttpURLConnection httpConnection = (HttpURLConnection) connection

int responseCode = httpConnection.getResponseCode()

if (responseCode == HttpURLConnection.HTTP_OK) {

inStream = httpConnection.getInputStream()

BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"))

StringBuilder strber = new StringBuilder()

while ((line = reader.readLine()) != null)

strber.append(line + "\n")

inStream.close()

// 从反馈的结果中提取出IP地址

int start = strber.indexOf("{")

int end = strber.indexOf("}")

String json = strber.substring(start, end + 1)

if (json != null) {

try {

JSONObject jsonObject = new JSONObject(json)

line = jsonObject.optString("cip")

} catch (JSONException e) {

e.printStackTrace()

}

}

return line

}

} catch (MalformedURLException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

return line

}

public static String getLocalMacAddress() {//没有缓存的地址,则查询

String mac_s = "" try {byte[] mac

NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()))

mac = ne.getHardwareAddress()

mac_s = byte2hex(mac)

} catch (Exception e) {

}mac_s return mac_s

}