前几天接到个任务,要求批量ping域名,找了网上好多资料都没有好的方法,只能自己试着用外部工具fping辅助,做了一个工具类,用了下还可以
首先安装fping
yum -y install fping
然后给普通用户权限
chown root:root /usr/local/sbin/fping
chmod u+s /usr/local/sbin/fping
下面是工具类
public class NetUtils {
private static final String ALIVE = "alive";
private static final String FPING = "fping ";
private static final String IS = " is ";
private static final String COLON = ":";
private static final String CHARSET = "UTF-8";
private static final String UNREACHABLE= "unreachable";
//单独ping一个的,格式 fping baidu.com
public static boolean ping(String ipAddress) {
BufferedReader br = null;
String pingCommand = FPING + ipAddress;
try {
Process p = Runtime.getRuntime().exec(pingCommand);
br = new BufferedReader(new InputStreamReader(p.getInputStream(), CHARSET));
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains(ALIVE)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
//ping多个的,格式 fping baidu.com douyin.com 12.45.43.211 多个域名网址中间以空格隔开,返回的是域名是否在线: key<域名> value<alive或unreachable>
public static Map<String, String> fPing(String ipAddress) {
BufferedReader br = null;
String pingCommand = FPING + ipAddress;
HashMap<String, String> map = new HashMap<>();
try {
Process p = Runtime.getRuntime().exec(pingCommand);
br = new BufferedReader(new InputStreamReader(p.getInputStream(), CHARSET));
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains(IS)) {
String[] split = line.split(IS);
map.put(split[0], split[1]);
}else {
String[] split = line.split(COLON);
map.put(split[0],UNREACHABLE);
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
}
试了一下,200多个IP/域名,用javaping跑了5分钟,这个用了30秒