81,122
社区成员




import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class GetClientMacAddr {
static int iRemotePort = 137;
static byte[] msg = { 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4B,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x00, 0x00, 0x21, 0x00, 0x01 };
public String GetRemoteMacAddr(String sRemoteAddr) {
byte[] buffer = new byte[1024];
StringBuffer sb = new StringBuffer(17);
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
DatagramPacket dps = new DatagramPacket(msg, msg.length, InetAddress.getByName(sRemoteAddr), iRemotePort);
ds.send(dps);
DatagramPacket dpr = new DatagramPacket(buffer, buffer.length);
ds.receive(dpr);
byte[] brevdata = dpr.getData();
int i = brevdata[56] * 18 + 56;
String sAddr = "";
for (int j = 1; j < 7; j++) {
sAddr = Integer.toHexString(0xFF & brevdata[i + j]);
if (sAddr.length() < 2) {
sb.append(0);
}
sb.append(sAddr.toUpperCase());
if (j < 6)
sb.append(':');
}
return sb.toString();
} catch (SocketException e) {
// Exception in new DatagramSocket();
e.printStackTrace();
} catch (UnknownHostException e) {
// Exception in dgs
e.printStackTrace();
} catch (IOException e) {
// Exception send & receive
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
return "";
}
}
局部变量,不用搞成为类属性;
cmd数据是不变的,写成数组初值,使用赋值语句太浪费
GetRemoteMacAddr写成一个函数足够小,分成多个无法做异常处理,e.printStackTrace();可以替换为日志输出或临时的控制台输出。还有一个超时异常没有处理
取消了增加的构造函数