java中获取mac 地址

通过IP地址获取远程MAC地址:

public static String getMacAddressIP(String remotePcIP) {
String str = "";
String macAddress = "";
try {
Process pp = Runtime.getRuntime().exec("nbtstat -A " + remotePcIP);
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(
str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException ex) {
}
return macAddress;
}


在windows中获取MAC地址:

public class Test {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("ipconfig /all");
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null)
if (line.indexOf("Physical Address") > 0) {
String MACAddr = line.substring(line.indexOf("-") - 2);
System.out.println("MAC address = [" + MACAddr + "]");
}
} catch (java.io.IOException e) {
System.err.println("IOException " + e.getMessage());
}
}
}



linux下获取ip地址:
public static byte[] getIp() throws UnknownHostException {
byte[] b = InetAddress.getLocalHost().getAddress();
Enumeration allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress ip = null;
NetworkInterface netInterface = null;
while (allNetInterfaces.hasMoreElements()) {
netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.getName().trim().equals("eth0")){
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
}
break;
}
}
if (ip != null && ip instanceof Inet4Address) {
return b = ip.getAddress();
}
return b;
}


NETBIOS,据说可以远程获取,且仅限于Windows主机,但我没有成功过,一跨网段就没戏。Linux下有工具nbtscan。


Process p = Runtime.getRuntime().exec("nbtscan -r " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
System.out.println(str);
if(str.startsWith(ip))
{
str=str.substring(str.lastIndexOf(" ")+1).trim();
System.out.println(str);
if(ValidMac(str))
macAddress=str.toUpperCase();
break;
}
}


 /** 
* 获取unix网卡的mac地址.
* 非windows的系统默认调用本方法获取.如果有特殊系统请继续扩充新的取mac地址方法.
* @return mac地址
*/
public static String getUnixMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("ifconfig eth0");// linux下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
bufferedReader = new BufferedReader(new InputStreamReader(process
.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("hwaddr");// 寻找标示字符串[hwaddr]
if (index >= 0) {// 找到了
mac = line.substring(index +"hwaddr".length()+ 1).trim();// 取出mac地址并去除2边空格
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}

return mac;
}

这是在JDK1.6以后的好方法
public String getMacAddress(String host)   
{
String mac = "";
StringBuffer sb = new StringBuffer();

try
{
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(host));

byte[] macs = ni.getHardwareAddress();

for(int i=0; i<macs.length; i++)
{
mac = Integer.toHexString(macs[i] & 0xFF);

if (mac.length() == 1)
{
mac = '0' + mac;
}

sb.append(mac + "-");
}

} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}

mac = sb.toString();
mac = mac.substring(0, mac.length()-1);

return mac;
}

jdk1.6的另一种算法
 public static void main(String[] args) {        try {            //InetAddress address = InetAddress.getLocalHost();            InetAddress address = InetAddress.getByName("192.168.46.53");            /*             * Get NetworkInterface for the current host and then read the             * hardware address.             */            NetworkInterface ni = NetworkInterface.getByInetAddress(address);            if (ni != null) {                byte[] mac = ni.getHardwareAddress();                if (mac != null) {                    /*                     * Extract each array of mac address and convert it to hexa with the                     * following format 08-00-27-DC-4A-9E.                     */                    for (int i = 0; i < mac.length; i++) {                        System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");                    }                } else {                    System.out.println("Address doesn't exist or is not accessible.");                }            } else {                System.out.println("Network Interface for the specified address is not found.");            }        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (SocketException e) {            e.printStackTrace();        }    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值