小弟看到网络编程部分..发现只有获取套接字(即获取端口号跟IP地址)但是却没有获取MAC地址的方法..求指教!

解决方案 »

  1.   

    记得有个第三方开发的DLL可以直接获取,以前找到过
    GO一下
      

  2.   

    这东西有的难度吧,java支持到网络层编程,获取底层物理层的东西……
      

  3.   

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

  4.   

    byte[] mac = ni.getHardwareAddress();
    这个地方报错!!什么情况是不是赋值有问题啊
      

  5.   

    刚刚找到个好的..大家一起来分享一下啊
    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();
            }
        }
    }
      

  6.   

    好好研习研习下面几个类。
    InetAddress 
    NetworkInterface
    看看有什么方法可用 
      

  7.   

    还有一种方法可以通过系统命令还获取
    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);
        }
    }
      

  8.   

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

  9.   

    [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……
    [/QuotegetHardwareAddress()is undefined
      

  10.   

    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;
      

  11.   

    就是让你查看一下你的jdk版本
    执行一下
    java -version
    命令,看看版本是什么?
    执行
    javap java.net.NetworkInterface | grep getH
    查看是否有getHardwareAddress方法
    windows系统的话执行
    javap java.net.NetworkInterface | findstr getH
      

  12.   


    mac地址只能在本机运行得到.远程得到,需要获得其他命令的输出,这不是tcpip层能解决.有些mac不太准,所以还是用ip就得了.
      

  13.   

    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"));
    }
    }