January 29, 2014

How to fetch Mac ID of Client machine using Java Applet in a web based application?


1). You need to download "java-plugin-1.6.0.23.jar
2). Create a Java Project "GetClientMacID". Project Structure will look like this:

3). Create a Java Applet "MacIDFinder"

import java.applet.Applet;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import netscape.javascript.JSObject;

public class MacIDFinder extends Applet
{
    public static String sep = ":";

    public static String getMacFromInterface(NetworkInterface ni) throws SocketException
    {
        byte mac[] = ni.getHardwareAddress();
        if (mac != null)
        {
            StringBuilder macAddress = new StringBuilder("");
            String sep = "";
            for (byte o : mac)
            {
                macAddress.append(sep).append(String.format("%02X", o));
                sep = ":";
            }
            return macAddress.toString();
        }
        return "";
    }

    public static String[] getInterfaces()
    {
        try
        {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            ArrayList result = new ArrayList();
            while (nis.hasMoreElements())
            {
                NetworkInterface ni = nis.nextElement();
                if (ni.isUp() && !ni.isLoopback() && !ni.isVirtual()) {
                    String mac = getMacFromInterface(ni);
                    String str = mac;//ni.getDisplayName() + ";" + mac;
                    result.add(str);
                }
            }
            return result.toArray(new String[0]);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return new String[0];
    }
    public static String getInterfacesJSON() {
        try
        {
            String macs[] = getInterfaces();

            String sep = "";
            StringBuilder macArray = new StringBuilder("");
            for (String mac : macs)
            {
                macArray.append(sep).append(mac);
                sep = "','";
            }
            macArray.append("");

            return macArray.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "[]";
    }
    public static void setSep( String sep )
    {
        try {
            MacIDFinder.sep = sep;
        } catch( Exception ex ) {          
        }
    }
    @Override
    public void start()
    {
        JSObject window = JSObject.getWindow(this);
        String macid=getInterfacesJSON();
        System.out.println( "Mac ID Of Client is: " + macid );
        window.call("setMacAddress", new Object[] {macid})   ;
    }  
}


4).  Now create a "build.xml"  file:

<project>
    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build"/>
        <javac srcdir="." destdir="build" classpath="./java-plugin-1.6.0.23.jar"/>
    </target>

    <target name="jar">
        <mkdir dir="build"/>
        <jar destfile="build/macidfinder.jar" basedir="build">
            <manifest>
                <attribute name="Main-Class" value="MacIDFinder"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="build/macidfinder.jar" fork="true"/>
    </target>
</project>


5). Drag and drop above Build.xml on Ant View:
6). Now execute clean, compile and jar, which will generate "macidfinder.jar" in build folder:

7). To need to sign the jar before embedding the applet in JSP. 

Why need to sign Java Applet? Java applets are living in a restricted environment so called “sandbox”, when it is running inside web browser. This prevents the applets from accessing system resources and devices such as files, network connections, printers, cameras, microphones, etc, without user-granted permission. This tight security is designed to make users safe from malicious code which always tries to execute automatically without user’s intervention.

Go to the command prompt and execute below command, which will generate the key which will be used for Jar Signing:

keytool -genkey -alias macid123 -validity 30

 Where "macid123" is test alias.  -validity 30  means your key has a validity of 30 days. if not specified the certificate that you are generating and signing has a default validity for 180 days. 

D:\>keytool -genkey -alias macid123 -validity 30
Enter keystore password:
mac768
 Re-enter new password:mac768
What is your first and last name?
  [Unknown]:  K Himaanshu Shukla
What is the name of your organizational unit?
  [Unknown]:  Scrutiny
What is the name of your organization?
  [Unknown]:  Scrutiny
What is the name of your City or Locality?
  [Unknown]:  Mumbai
What is the name of your State or Province?
  [Unknown]:  Maharastra
What is the two-letter country code for this unit?
  [Unknown]:  91
Is CN=K Himaanshu Shukla, OU=Scrutiny, O=Scrutiny, L=Mumbai, ST=Maharastra, C=91
 correct?
  [no]:  y

Enter key password for <macid123>
        (RETURN if same as keystore password):
mac768
Re-enter new password:mac768

8).  To sign the jar execute the below command:
jarsigner macidfinder.jar  macid123

It will ask you for the password which you have specified in step 7.

D:\>jarsigner macidfinder.jar  macid123
Enter Passphrase for keystore: mac768
jarsigner: unable to open jar file: macidfinder.jar


9).  Now create a jsp in which you will be embedding the above applet:

<table>
<tr>
<td>
<applet width="50" height="50" code="MacIDFinder.class" codebase="${pageContext.request.contextPath}"  archive="
macidfinder.jar, java-plugin-1.6.0.23.jar"></applet>
<input type="hidden" id="maccid" name="maccid" />
</td>
</tr>
</table>


10).  Copy macidfinder.jar, java-plugin-1.6.0.23.jar in the same location where your JSP is present.

11).  Add the below java script code in your JSP.

 <script>
function
setMacAddress(macaddress)
{
document.forms[0].maccid.value=
macaddress;
}
</script>



setMacAddress()  will be called from the start() method of MacIDFinder from the below code:

window.call("setMacAddress", new Object[] {macid})  ;

 setMacAddress()  java script will set the fetched Mac ID in hidden variable.

-K Himaanshu Shukla

14 comments:

  1. I really like this blogpost. It helped me a lot in my project.

    Thanks mate

    ReplyDelete
  2. Hi ,
    I am getting class not found exception in the applet i.e MACIDFinder.class,when i am run in the browser.please help how to integrate in my application.

    ReplyDelete
    Replies
    1. whr hv u kept MACIDFinder.class??????

      Delete
  3. Hi everybody, does this project work?

    ReplyDelete
  4. rdsdetailfinder.jar from wer u get

    ReplyDelete
  5. Sorry by mistake I mentioned wrong name of jar...Kindly replace rdsdetailfinder.jar name with macidfinder.jar

    ReplyDelete
  6. MACIDFinder.class is present in macidfinder.jar

    ReplyDelete
  7. Hi,

    This project is not working ,
    Plesae help

    ReplyDelete
  8. Dear Vineet, Please let me know, what error you are getting.

    ReplyDelete
  9. can u pls send this project to me my mail id is sudharshansree@gmail.com

    ReplyDelete
  10. This Project is not working for me, am using JDK1.8.. Kindly send me the project to my mail id - prabup.rajendran@gmail.com.

    ReplyDelete
  11. can u please send this project in my mail id milansingh1092@gmail.com

    ReplyDelete