Linux平臺下JAVA通過命令(如ifconfig)或讀取文件獲取網絡接口

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Title:  NetInterfaceUtil.java
 * Package 
 * Description:    通過命令或讀取文件方式獲取網絡接口參數(IP,MAC)
 * Date:   2019年12月10日
 * @author: RenEryan
 * @version V1.0
 * Copyright (c) 2019 www.sunkaisens.com Inc. All rights reserved.
 */

/**
 * Description:TODO
 * 
 * @author RenEryan
 * @since 2019年12月10日
 */
public class NetInterfaceUtil {
	
	private final static String testCmdRlt = "eth0      Link encap:Ethernet  HWaddr D0:67:26:9C:B1:A4  \n" + 
			"          inet addr:172.16.0.203  Bcast:172.16.0.255  Mask:255.255.255.0\n" + 
			"          inet6 addr: fe80::d267:26ff:fe9c:b1a4/64 Scope:Link\n" + 
			"          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n" + 
			"          RX packets:45795974 errors:0 dropped:0 overruns:0 frame:0\n" + 
			"          TX packets:41266134 errors:0 dropped:0 overruns:0 carrier:0\n" + 
			"          collisions:0 txqueuelen:1000 \n" + 
			"          RX bytes:5235741155 (4.8 GiB)  TX bytes:21782144988 (20.2 GiB)\n" + 
			"          Interrupt:18";

	private final static String testCmdRlt2 = "eth2: ip 170.130.12.3 mask 255.255.255.0 flags [up broadcast running multicast]";

	public static void main(String[] args) {
		
		//生成可執行jar包。
		if (args.length < 1) {
			System.err.println("please input interface name, such as: NetInterfaceUtil eth0");
		}
		try {
			System.err.println(getNetInterfaceIp(args[0]));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//測試語句
		System.err.println(getCmdRltIP(testCmdRlt));
		System.err.println(getCmdRltIP(testCmdRlt2));
		
	}

	/**
	 * Linux平臺通過ifconfig命令獲取指定接口名稱的IP地址
	 * 
	 * @param input
	 * @return
	 * @return String
	 */
	public static String getNetInterfaceIp(String IntfName) {
//		if (System.getProperty("os.name").equals("Linux")) {  //windows下測試,註釋此語句
			String cmdResult = null;
			try {
				
				cmdResult = execCmd("ifconfig " + IntfName, null);
				//cmdResult可能是: 
				Pattern p = Pattern.compile("inet addr:(\\d+\\.\\d+\\.\\d+\\.\\d+)");
				Matcher m = p.matcher(cmdResult);
				// 將符合規則的提取出來
				while (m.find()) {
					return m.group(1);
				}
				
				//cmdResult可能是: "eth2: ip 170.130.12.3 mask 255.255.255.0 flags [up broadcast running multicast]";
				p = Pattern.compile("eth2: ip (\\d+\\.\\d+\\.\\d+\\.\\d+)");
				m = p.matcher(cmdResult);
				// 將符合規則的提取出來
				while (m.find()) {
					System.out.print(m.group(1));
				}
				
			} catch (Exception e) {
				return null;
			}
//		}
		return null;
	}

	/**
	 * Linux平臺獲取命令運行後的IP地址
	 * 
	 * @param input
	 * @return
	 * @return String
	 */
	public static String getCmdRltIP(String cmdResult) {
//		if (System.getProperty("os.name").equals("Linux")) { //windows下測試,註釋此語句
			try {
				Pattern p = Pattern.compile("inet addr:(\\d+\\.\\d+\\.\\d+\\.\\d+)");
				Matcher m = p.matcher(cmdResult);
				// 將符合規則的提取出來
				while (m.find()) {
					return m.group(1);
				}
				
				//cmdResult可能是: "eth2: ip 170.130.12.3 mask 255.255.255.0 flags [up broadcast running multicast]";
				p = Pattern.compile("eth2: ip (\\d+\\.\\d+\\.\\d+\\.\\d+)");
				m = p.matcher(cmdResult);
				// 將符合規則的提取出來
				while (m.find()) {
					return m.group(1);
				}
				
			} catch (Exception e) {
				return null;
			}
//		}
		return null;
	}
	
	/**
	 * 執行系統命令, 返回執行結果
	 *
	 * @param cmd 需要執行的命令
	 * @param dir 執行命令的子進程的工作目錄, null 表示和當前主進程工作目錄相同
	 */
	public static String execCmd(String cmd, File dir) throws Exception {
		StringBuilder result = new StringBuilder();

		Process process = null;
		BufferedReader bufrIn = null;
		BufferedReader bufrError = null;

		try {
			// 執行命令, 返回一個子進程對象(命令在子進程中執行)
			process = Runtime.getRuntime().exec(cmd, null, dir);

			// 方法阻塞, 等待命令執行完成(成功會返回0)
			process.waitFor();

			// 獲取命令執行結果, 有兩個結果: 正常的輸出 和 錯誤的輸出(PS: 子進程的輸出就是主進程的輸入)
			bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
			bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GBK"));

			// 讀取輸出
			String line = null;
			while ((line = bufrIn.readLine()) != null) {
				result.append(line).append('\n');
			}
			while ((line = bufrError.readLine()) != null) {
				result.append(line).append('\n');
			}

		} finally {
			closeStream(bufrIn);
			closeStream(bufrError);

			// 銷燬子進程
			if (process != null) {
				process.destroy();
			}
		}

		// 返回執行結果
		return result.toString();
	}

	private static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (Exception e) {
				// nothing
			}
		}
	}

	/**
	 * 獲取MAC地址
	 * 
	 * @throws SocketException
	 * @return void
	 */
	public void printHardwareAddresses() throws SocketException {
		if (System.getProperty("os.name").equals("Linux")) {
			// Read all available device names
			List<String> devices = new ArrayList<String>();
			Pattern pattern = Pattern.compile("^ *(.*):");
			try {
				FileReader reader = new FileReader("/proc/net/dev");
				BufferedReader in = new BufferedReader(reader);
				String line = null;
				while ((line = in.readLine()) != null) {
					Matcher m = pattern.matcher(line);
					if (m.find()) {
						devices.add(m.group(1));
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			// read the hardware address for each device
			for (String device : devices) {
				try {
					FileReader reader = new FileReader("/sys/class/net/" + device + "/address");
					BufferedReader in = new BufferedReader(reader);
					String addr = in.readLine();

					System.out.println(String.format("%5s: %s", device, addr));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

 

發佈了6 篇原創文章 · 獲贊 3 · 訪問量 3031
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章