Java调用ping命令

package cn.com.songjy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Ping {

public static void main(String[] args) throws IOException {
System.out.println(ping("127.0.0.1", 1));
System.out.println("************************************");
System.out.println(ping("www.baidu.com", 35));
}

/**
*
* @param target_name
* IP地址或域名
* @param out_time
* 超时间隔,单位为毫秒
* @return
* @throws IOException
*/
public static boolean ping(String target_name, int out_time)
throws IOException {

Runtime runtime = Runtime.getRuntime();

String ping_command = "ping " + target_name + " -w " + out_time;

System.out.println("命令格式:" + ping_command);

Process process = runtime.exec(ping_command);

if (null == process)
return false;

BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream(), "GBK"));// windows下编码默认是GBK,Linux是UTF-8

String line = null;

while (null != (line = bufferedReader.readLine())) {

System.out.println(line);

if (line.startsWith("Reply from"))
return true;
if (line.startsWith("来自"))
return true;
}

bufferedReader.close();

return false;
}

}
/* 这里只是简单检测是否能通,如果还需要更详细信息可查看ping命令的介绍 */


效果图如下:
[img]http://dl2.iteye.com/upload/attachment/0091/5443/dc40feaa-cd03-3f87-ad6a-74e6005d0b1a.png[/img]

以下来自[url=http://www.zuidaima.com/share/2197410982677504.htm]java Ping域名网络工具类PingUtils.java源代码分享[/url]
package demo;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class PingUtils {

public static Domain ping(String domian) {
long start = System.currentTimeMillis();
Domain result = new Domain();
try {
InetAddress address = InetAddress.getByName(domian);
result.ip = address.getHostAddress();
result.host = address.getHostName();
long end = System.currentTimeMillis();
result.time = (end - start);
} catch (UnknownHostException e) {
result.ip = "0.0.0.0";
result.host = "UNKONW";
}
return result;
}

public static class Domain {
String ip;
String host;
long time;

@Override
public String toString() {
return String.format("host=%s, ip=%s, time=%s", host, ip, time);
}
}

public static void main(String[] args) {
Domain domain = ping("www.baidu.com");
System.out.println(domain);
}
}

效果如下:
[img]http://dl2.iteye.com/upload/attachment/0106/9914/c0505c2c-f733-3b9e-a24e-5ed323565636.png[/img]

[url=http://kongcodecenter.iteye.com/blog/1231177]java 调用shell命令[/url]

[url=http://www.oschina.net/code/snippet_47886_20136]java使用dos命令创建文件夹[/url]

[url=http://blog.163.com/zhao_jinggui/blog/static/169620429201161163711467/]JAVA执行bat文件和shell脚本文件[/url]

[url=http://blog.sina.com.cn/s/blog_63c8c46401017y7r.html]del命令和rd命令[/url]
[img]http://dl2.iteye.com/upload/attachment/0092/8082/5b3732ab-3cb1-3f32-b973-a441de2e3fb8.png[/img]

你可能感兴趣的:(Java,Linux,IO)