如何获取IP地址对应的MAC地址

luzhiqin 2011-05-25 10:18:20
小弟看到网络编程部分..发现只有获取套接字(即获取端口号跟IP地址)但是却没有获取MAC地址的方法..求指教!
...全文
425 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
hy158753228 2011-05-25
  • 打赏
  • 举报
回复
package csdn.impulsehu.may;

import java.net.InetAddress;
import java.net.NetworkInterface;

public class MacAddressTest {
public static void main(String[] args) {
System.out.println(getMacAddress());
}

private static String getMacAddress() {
InetAddress ia = null;
NetworkInterface ni = null;
byte[] bytes = null;
String macAdd = "";

try {
ia = InetAddress.getLocalHost();
ni = NetworkInterface.getByInetAddress(ia);
bytes = ni.getHardwareAddress();
for(int i=0; i<bytes.length; i++) {
if(bytes[i] != 0) {
if(bytes[i] >= 0) {
macAdd = macAdd + Integer.toHexString(bytes[i]) + "-";
} else {
macAdd = macAdd + Integer.toHexString(bytes[i]).substring(6) + "-";
}
} else {
macAdd = macAdd + "00" + "-";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return macAdd.substring(0, macAdd.length()-1).toUpperCase();
}
}
qybao 2011-05-25
  • 打赏
  • 举报
回复
还有一种方法可以通过系统命令还获取
Process p = Runtime.getRuntime().exec("ipconfig /all");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
for (String s=br.readLine(); s!=null; s=br.readLine()) {
if (s.indexOf("Physical") >= 0) {
System.out.println(s);
}
}
moon&sean 2011-05-25
  • 打赏
  • 举报
回复
好好研习研习下面几个类。
InetAddress
NetworkInterface
看看有什么方法可用
luzhiqin 2011-05-25
  • 打赏
  • 举报
回复
刚刚找到个好的..大家一起来分享一下啊
package com.luzhiqin.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IpUtil {
private static final String[] windowsCommand = { "ipconfig", "/all" };
private static final String[] linuxCommand = { "/sbin/ifconfig", "-a" };
private static final Pattern macPattern = Pattern
.compile(".*((:?[0-9a-f]{2}[-:]){5}[0-9a-f]{2}).*",
Pattern.CASE_INSENSITIVE);

private final static List getMacAddressList() throws IOException {
final ArrayList macAddressList = new ArrayList();

final String os = System.getProperty("os.name");

final String[] command;
if (os.startsWith("Windows")) {
command = windowsCommand;
} else if (os.startsWith("Linux")) {
command = linuxCommand;
} else {
throw new IOException("Unknown operating system: " + os);
}

final Process process = Runtime.getRuntime().exec(command);
// Discard the stderr
new Thread() {
public void run() {
try {
InputStream errorStream = process.getErrorStream();
while (errorStream.read() != -1) {
}
errorStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();

// Extract the MAC addresses from stdout
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
for (String line = null; (line = reader.readLine()) != null;) {
Matcher matcher = macPattern.matcher(line);
if (matcher.matches()) {
// macAddressList.add(matcher.group(1));
macAddressList.add(matcher.group(1).replaceAll("[-:]", ""));
}
}
reader.close();
return macAddressList;
}

public static String getMacAddress() {
try {
List addressList = getMacAddressList();
StringBuffer sb = new StringBuffer();
for (Iterator iter = addressList.iterator(); iter.hasNext();) {
sb.append("\n").append(iter.next());
}
return sb.toString();
} catch (IOException e) {
return null;
}
}
public final static void main(String[] args) {
try {
System.out.println(" MAC Address: " + getMacAddress());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
luzhiqin 2011-05-25
  • 打赏
  • 举报
回复
byte[] mac = ni.getHardwareAddress();
这个地方报错!!什么情况是不是赋值有问题啊
血战31天 2011-05-25
  • 打赏
  • 举报
回复
java取得网卡地址
String macStr = "";//MAC网卡地址
try {
InetAddress address = InetAddress.getLocalHost();//取得本地Ip地址
System.out.println("getLocalHost:" + address.toString());
//InetAddress address = InetAddress.getByName("192.168.46.53");
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
macStr = macStr + String.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 ex) {
ex.printStackTrace();
} catch (SocketException ex1) {
ex1.printStackTrace();
}
System.out.println("macStr:" + macStr);
okgoood 2011-05-25
  • 打赏
  • 举报
回复
帮 顶
caibird1024 2011-05-25
  • 打赏
  • 举报
回复
这东西有的难度吧,java支持到网络层编程,获取底层物理层的东西……
luzhiqin 2011-05-25
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wu_yeah 的回复:]
记得有个第三方开发的DLL可以直接获取,以前找到过


GO一下
[/Quote]
应该可以写个java程序获得吧
WU_YEAH 2011-05-25
  • 打赏
  • 举报
回复
记得有个第三方开发的DLL可以直接获取,以前找到过


GO一下
flytomylife1 2011-05-25
  • 打赏
  • 举报
回复
学习下 呵呵~
lord_is_layuping 2011-05-25
  • 打赏
  • 举报
回复


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
* @ClassName: MacAddress
* @Description:
* @author LiangO
* @date 2011-05-25 16:41:51
*
*/
public class MacAddress {

/**
* @Title: getMacAddress
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param string
* @param @return 设定文件
* @return char[] 返回类型
* @throws
*/
private static String getMacAddress(String ip) {
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.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 e) {
e.printStackTrace(System.out);
}
return macAddress;

}

public static void main(String[] args) {

System.out.println(getMacAddress("192.168.1.2"));
}
}

caoze 2011-05-25
  • 打赏
  • 举报
回复

mac地址只能在本机运行得到.

远程得到,需要获得其他命令的输出,这不是tcpip层能解决.

有些mac不太准,所以还是用ip就得了.
xiao_cs 2011-05-25
  • 打赏
  • 举报
回复
上面贴了好多代码哦 帮顶一个
qybao 2011-05-25
  • 打赏
  • 举报
回复
就是让你查看一下你的jdk版本
执行一下
java -version
命令,看看版本是什么?
执行
javap java.net.NetworkInterface | grep getH
查看是否有getHardwareAddress方法
windows系统的话执行
javap java.net.NetworkInterface | findstr getH


luzhiqin 2011-05-25
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 huntor 的回复:]
引用 12 楼 luzhiqin 的回复:

getHardwareAddress()is undefined

java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) Client VM (build 20.0-b11, m……
[/Quote]
不懂
huntor 2011-05-25
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 luzhiqin 的回复:]

getHardwareAddress()is undefined
[/Quote]
java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) Client VM (build 20.0-b11, mixed mode, sharing)

javap java.net.NetworkInterface | grep getH
public byte[] getHardwareAddress() throws java.net.SocketException;
luzhiqin 2011-05-25
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 hy158753228 的回复:]
Java code
package csdn.impulsehu.may;

import java.net.InetAddress;
import java.net.NetworkInterface;

public class MacAddressTest {
public static void main(String[] args) {
System……
[/Quote

getHardwareAddress()is undefined
caibird1024 2011-05-25
  • 打赏
  • 举报
回复
有能获取远程的吗

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧