JAVA obtains the physical address of the NIC (windows and Linux)-Linux general technology-Linux programming and kernel information. For more information, see the following. In the process of writing a program, we sometimes need to know some computer hardware information. For example, when we write a program that needs to be registered, we need to obtain a specific computer information, in general, the physical address of the network card will not be repeated. We can use it as a sign for us to identify a computer. how can we get the physical address of the Nic? We can use the ProcessBuilder class, which is newly added by JDK1.5. We can also use Runtime in the past. exce class. here we will demonstrate how to obtain the physical address of the NIC in Windows and Linux environments.
CODE :/* * Test. java * * Created on, 9:11:15 * * To change this template, choose Tools | Templates * And open the template in the editor. */
Package test2;
Import java. io. BufferedReader; Import java. io. IOException; Import java. io. InputStreamReader; Import java. util. Properties; Import java. util. logging. Level; Import java. util. logging. Logger;
/** * * @ Author hadeslee */ Public class Test {
Public static String getMACAddress (){
String address = ""; String OS = System. getProperty ("OS. name "); System. out. println (OS ); If (OS! = Null ){ If (OS. startsWith ("Windows ")){ Try { ProcessBuilder pb = new ProcessBuilder ("ipconfig", "/all "); Process p = pb. start (); BufferedReader br = new BufferedReader (new InputStreamReader (p. getInputStream ())); String line; While (line = br. readLine ())! = Null ){ If (line. indexOf ("Physical Address ")! =-1 ){ Int index = line. indexOf (":"); Address = line. substring (index + 1 ); Break; } } Br. close (); Return address. trim (); } Catch (IOException e ){ } } Else if (OS. startsWith ("Linux ")){ Try { ProcessBuilder pb = new ProcessBuilder ("ifconfig "); Process p = pb. start (); BufferedReader br = new BufferedReader (new InputStreamReader (p. getInputStream ())); String line; While (line = br. readLine ())! = Null ){ Int index = line. indexOf ("hardware address "); If (index! =-1 ){ Address = line. substring (index + 4 ); Break; } } Br. close (); Return address. trim (); } Catch (IOException ex ){ Logger. getLogger (Test. class. getName (). log (Level. SEVERE, null, ex ); } } } Return address; }
Public static void main (String [] args ){ System. out. println ("" + Test. getMACAddress ()); } } |