JAVA MacUtil

package reflect;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class MacUtil {
	
	public String getMACAddress2(String ip){

	    String str = "";  
	    String macAddress = "";  
	    try {  
	    	Process pp = Runtime.getRuntime().exec("ping " + ip);  
	    	
	        Process p = Runtime.getRuntime().exec("arp -a");  
	        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(ip) > 1) {  
	                    macAddress = str.substring(str.indexOf(ip) + 22, 41).toUpperCase();  
	                    if("00-00-00-00-00-00".equals(macAddress)){
	                    	macAddress = null;
	                    }
	                    ir.close();
	                    input.close();
	                    break;  
	                }  
	            }  
	        }  
	    } catch (IOException e) {  
	        e.printStackTrace(System.out);  
	    }  
	    return macAddress; 
	}
	
	public 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());  
	                    ir.close();
	                    input.close();
	                    break;  
	                }  
	            }  
	        }  
	    } catch (IOException e) {  
	        e.printStackTrace(System.out);  
	    }  
	    if(macAddress==null || "".equals(macAddress)){
	    	macAddress = this.getMACAddress2(ip);
	    }
	    return macAddress; 
	}
	
	public static void main(String[] args) {
		MacUtil m = new MacUtil();
		System.out.println(m.getMACAddress("192.168.0.123"));
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章