Implement MAC address reading by programming in Java only

Source: Internet
Author: User

1 Introduction

Programs Written in Java can be conveniently run in various platform environments. However, in the actual development process, some underlying programming is sometimes required. For example, in order to prevent software theft, we hope that the software can only run on a specified computer, so the program needs to read the hardware features of the machine, such as the MAC address, which is differentiated from other computers. As a cross-platform language, this poses a challenge to the Java language. To solve this problem, this article proposes a programming method to read MAC addresses directly using pure Java.

We know that there is a runtime object associated with the runtime environment in every Java application. This object can execute External commands and check available memory. Most operating systems provide commands for querying the MAC address of the machine. For example, the command ipconfig is used in Microsoft's operating system. The idea of this article is to run an external command in a program and read and analyze the running result of the command as a stream to obtain the MAC address.

2 Runtime class

Each Java application has a unique runtime object. Through this runtime object, the application can interact with its runtime environment.

Generally, a runtime object is not instantiated. However, you can obtain reference to the current runtime object by calling the static method runtime. getruntime. Most methods of the runtime class are instance methods.

Runtime objects are mainly used to execute External commands, return idle memory, run the garbage collector, and load dynamic libraries.

Applets and other untrusted programs cannot call any runtime method because they do not cause a security exception (securityexception.

The following example demonstrates how to use the runtime object to run an external command.

The following is a reference clip:
:
Process = runtime.getruntime(cmd.exe C ("cmd.exe/C dir ");
Process. waitfor ();
:

Runtime. getruntime () returns the runtime object of the current application. The Exec () method of this object instructs the Java Virtual Machine to create a sub-process to execute the specified executable program, and return the process object instance corresponding to the sub-process. You can use process to control the execution of the sub-process or obtain information about the sub-process. The purpose of the second statement is to wait for the sub-process to complete and then execute it.

The above program runs the Dir command. In Windows 95/98, the command format can be "command.exe/C dir ". Switch/C: Specify the string followed by the command, and close the DOS window after executing the command.

Method exec can also open an unexecutable program, but the file has an associated application. The following two methods can be used in Java to open a wordfile mydoc.doc:

The following is a reference clip:
Exec ("" CMD/E: On/C start mydoc.doc "");
Exec ("C: Program filesmicrosoft officeofficewinword.exe .mydoc.doc ");

In the first method, the command to be executed is start mydoc.doc. Switch E: on to specify the DOS command processor to allow command extension, the START command opens a separate window to execute the provided command.

When you execute a standard output doscommand, the program will not be automatically closed after execution, leading to Java application blocking in waitfor (). The cause may be that the output buffer of the command is too large and the output buffer of the running window is not large enough. The solution is to use the Java Process class to allow the Java Virtual Machine to intercept the standard output of DOS and read the content of the buffer before the waitfor () command. Take the command dir as an example. A typical program is as follows:

The following is a reference clip:
:
String line;
Process = runtime.getruntime(cmd.exe C ("CMD/C dir ");
Bufferedreader = new bufferedreader (New inputstreamreader (process. getinputstream ()));
While (line = bufferedreader. Readline ())! =-1) system. Out. println (line );
Process. waitfor ();
: 3 Process

The runtime.exe C method creates a local process and returns an instance of the Process subclass. This instance can be used to control the process and obtain relevant information.

Abstract class process encapsulates a process and an ongoing program. It is mainly treated as a superclass of the type of the object created by the exec () method in the runtime class. Abstract class process mainly includes the following abstract methods.

Inputstream getinputstream (): returns an input stream that reads input from the process's out output stream.

Outputstream getoutputstream (): returns an output stream written and output from the in input stream of the process.

Int waitfor () throws interruptedexception: return the exit code returned by the process. This method will not be returned until the process that calls it is aborted.

4 Programming

The output format of ipconfig/All is analyzed first:

Figure 1

Figure 1 shows the behavior of the MAC address: "physical address...: 00-10-dc-a9-0b-2c ". To find the MAC address, we only need to find the string "physical address...:" to read a line of characters, we can find the MAC address. The following is a program snippet:

The following is a reference clip:
:
Process = runtime.getruntime(cmd.exe C ("CMD/C ipconfig/all ");
Bufferedreader =
New bufferedreader (New inputstreamreader (process. getinputstream ()));
While (line = bufferedreader. Readline ())! = NULL ){
If (line. indexof ("physical address .........:")! =-1 ){
If (line. indexof (":")! =-1 ){
Physicaladdress = line. substring (line. indexof (":") + 2 );
:

In the above program, a data stream buffer is generated using the sub-process to read the characters output by the command.

Based on the above Code, we have compiled a readmac class. See the source code of the following program:

The following is a reference clip:
Import java. Io .*;
Public class readmac {
Public static string physicaladdress = "read Mac error! ";
Public readmac (){
}
Public static string checkphysicaladdress (){
Try {
String line;
Process = runtime.getruntime(cmd.exe C ("CMD/C ipconfig/all ");
Bufferedreader = new bufferedreader (New inputstreamreader (process. getinputstream ()));
While (line = bufferedreader. Readline ())! = NULL ){
If (line. indexof ("physical address .........:")! =-1 ){
If (line. indexof (":")! =-1 ){
Physicaladdress = line. substring (line. indexof (":") + 2 );
Break; // locate Mac and launch a loop
}
}
}
Process. waitfor ();
} Catch (exception e ){
E. printstacktrace ();
}
Return physicaladdress;
}
Public static void main (string [] ARGs ){
System. Out. println ("the MAC address of the local machine is:" + readmac. checkphysicaladdress ());
}
}

Compile and run the program output result 2.

Figure 2

Because the MAC address of each computer is different, the running results of this program on different computers are different.

5 conclusion

As a cross-platform language, Java programs are generally not related to hardware, so they can run in different operating system environments. However, this makes it inconvenient to compile underlying programs.

Java applications all have a runtime object associated with their runtime environment. This object can be used to execute External commands, the command ipconfig output in Windows XP/NT/2000 contains a MAC address. The Java program compiled in this article executes the external command ipconfig and obtains the MAC address of the Local Machine by analyzing the input stream of the command. Because the ipconfig command is an operating system command, this method is convenient and reliable.

The program discussed above is suitable for the Windows XP/NT/2000 operating system, because it is based on the command ipconfig format of the operating system. Because different operating systems use different commands for reading MAC addresses and command output formats, this program cannot be directly applied to other systems. To port to other systems, you only need to slightly modify the output format of the command.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.