0

我写了一个小程序,它从本地计算机获取 MAC 地址。它在 eclipse 上运行良好,但目前我尝试通过浏览器运行它,但它没有。

经过一些调试后,我意识到这部分在浏览器上返回 null

InetAddress.getLocalHost();

谁能告诉我为什么?

编辑:

这是我在网上某处找到的代码:

   import java.applet.Applet;
import java.awt.Graphics;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class LoginApplet extends Applet {

    private static final long serialVersionUID = 1L;

    private String macAddress;

    public void init() {
        setMacAddress(getMacAddressFromClient());
    }

    public void paint(Graphics g)
    {
        String mac = getMacAddress();
        if(mac.isEmpty())
        {
            mac = "Empty";
        }
        g.drawString(mac,15,15);
    }


    public String getMacAddressFromClient() {
           String macAddr= ""; 
            InetAddress addr;
         try {
             addr = InetAddress.getLocalHost();

                macAddress += addr.getHostAddress();
                NetworkInterface dir = NetworkInterface.getByInetAddress(addr);
                byte[] dirMac = dir.getHardwareAddress();

                int count=0;
                for (int b:dirMac){
                 if (b<0) b=256+b;
                 if (b==0) {
                       macAddr=macAddr.concat("00"); 
                 }
                 if (b>0){

                  int a=b/16;
                  if (a==10) macAddr=macAddr.concat("A");
                  else if (a==11) macAddr=macAddr.concat("B");
                  else if (a==12) macAddr=macAddr.concat("C");
                  else if (a==13) macAddr=macAddr.concat("D");
                  else if (a==14) macAddr=macAddr.concat("E");
                  else if (a==15) macAddr=macAddr.concat("F");
                  else macAddr=macAddr.concat(String.valueOf(a));
                     a = (b%16);
                  if (a==10) macAddr=macAddr.concat("A");
                  else if (a==11) macAddr=macAddr.concat("B");
                  else if (a==12) macAddr=macAddr.concat("C");
                  else if (a==13) macAddr=macAddr.concat("D");
                  else if (a==14) macAddr=macAddr.concat("E");
                  else if (a==15) macAddr=macAddr.concat("F");
                  else macAddr=macAddr.concat(String.valueOf(a));
                 }
                 if (count<dirMac.length-1)macAddr=macAddr.concat("-");
                 count++;
                }

         } catch (UnknownHostException e) {
          // TODO Auto-generated catch block
          macAddr=e.getMessage();
         } catch (SocketException e) {
          // TODO Auto-generated catch block
          macAddr = e.getMessage();
         }
        return macAddr;
    }

    public String getMacAddress() {
        return macAddress;
    }

    public void setMacAddress(String macAddress) {
        this.macAddress += macAddress;
    }
}

在 Eclipse 中:addr 具有 localhost 地址

在浏览器(IE 和 chrome)中,addr 为空。

4

0 回答 0