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();
}
}
}
}
}