Java 中獲取MAC地址 和IP地址

悠悠隱於市發表於2011-03-28
package pack.java.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class SystemMessageUtil {
	/**
	 * 獲取作業系統名稱:
	 * @return
	 */
	private static String getOSName(){
		return System.getProperty("os.name").toLowerCase();
	}
	
	/**
	 * 獲取本地IP地址;
	 * @return
	 */
	private String getLocalIpAddress(){
		String ipAddress = null;
		try {
			ipAddress = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ipAddress;
	}
	
	/**
	 * 獲取本機的MAC地址;
	 * @return
	 */
	public String getLocalWindosMacAddress(){
		String mac = null;
		BufferedReader bufferReader = null;
		Process process = null;
		try {
			//windows 下顯示mac網路卡地址資訊;
			process = Runtime.getRuntime().exec("ipconfig /all");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		bufferReader = new  BufferedReader(new InputStreamReader(process.getInputStream()));
		
		String line = null;
		int index = -1;
		try {
			while ((line=bufferReader.readLine())!=null) {
				System.out.println(line);
				index = line.indexOf("Physical Address");
				
				if(index>=0){
					index = line.indexOf(":");
					if(index>=0){
						mac = line.substring(index+1).trim();
					}
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(bufferReader!=null){
					bufferReader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return mac;
	}
	
	public static  void main(String[]args) {
		// TODO Auto-generated method stub
		SystemMessageUtil messageUtil = new SystemMessageUtil();
		System.out.println(messageUtil.getLocalIpAddress());
		
	}
}

 

相關文章