Android中实现ping功能的多种⽅法详解
使⽤java来实现ping功能。并写⼊⽂件。为了使⽤java来实现ping的功能,有⼈推荐使⽤java的 ()⽅法来直接调⽤系统的Ping命令,也有⼈完成了纯Java实现Ping的程序,使⽤的是Java的NIO包(native io, ⾼效IO包)。但是设备检测只是想测试⼀个远程主机是否可⽤。所以,可以使⽤以下三种⽅式来实现:
1. Jdk1.5的InetAddresss⽅式
⾃从Java 1.5,java包中就实现了ICMP ping的功能。
使⽤时应注意,如果远程服务器设置了防⽕墙或相关的配制,可能会影响到结果。另外,由于发送ICMP请求需要程序对系统有⼀定的权限,当这个权限⽆法满⾜时, isReachable⽅法将试着连接远程主机的TCP端⼝ 7(Echo)。代码如下:
public static boolean ping(String ipAddress) throws Exception {
int timeOut = 3000; // 超时应该在3钞以上
boolean status = ByName(ipAddress).isReachable(timeOut); // 当返回值是true时,说明host是可⽤的,false则不可。
return status;
}
2. 最简单的办法,直接调⽤CMD
public static void ping1(String ipAddress) throws Exception {
String line = null;
try {
Process pro = Runtime().exec("ping " + ipAddress);
BufferedReader buf = new BufferedReader(new InputStreamReader(
while ((line = adLine()) != null)
System.out.println(line);
} catch (Exception ex) {
System.out.Message());
}
}
3.Java调⽤控制台执⾏ping命令
具体的思路是这样的:
通过程序调⽤类似“ping 127.0.0.1 -n 10 -w 4”的命令,这命令会执⾏ping⼗次,如果通顺则会输出类似“来⾃127.0.0.1的回复:字节=32 时间<1ms TTL=64”的⽂本(具体数字根据实际情况会有变化),其中中⽂是根据环境本地化的,有些机器上的中⽂部分是英⽂,但不论是中英⽂环境,后⾯的“<1ms TTL=62”字样总是固定的,它表明⼀次ping的结果是能通的。如果这个字样出现的次数等于10次即测试的次数,则说明127.0.0.1是百分之百能连通的。
技术上:具体调⽤dos命令⽤Runtime().exec实现,查看字符串是否符合格式⽤正则表达式实现。代码如下:
public static boolean ping2(String ipAddress, int pingTimes, int timeOut) {
BufferedReader in = null;
Runtime r = Runtime(); // 将要执⾏的ping命令,此命令是windows格式的命令
String pingCommand = "ping " + ipAddress + " -n " + pingTimes  + " -w " + timeOut;
try {  // 执⾏命令并获取输出
System.out.println(pingCommand);
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStream()));  // 逐⾏检查输出,计算类似出现=23ms TTL=62字样的次数
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
}  // 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
return connectedCount == pingTimes;
} catch (Exception ex) {
ex.printStackTrace();  // 出现异常则返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
Pattern pattern = Patternpile("(\\d+ms)(\\s+)(TTL=\\d+)",  Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
return 1;
}
return 0;
}
4. 实现程序⼀开始就ping,运⾏完之后接受ping,并写⼊⽂件
完整代码如下:
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.InetAddress;
import java.MalformedURLException;
import java.URL;
SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import Matcher;
import Pattern;
public class Ping {
private static final String TAG = "Ping";
private static Runtime runtime;
private static Process process;
private static File pingFile;
/**
* Jdk1.5的InetAddresss,代码简单
* @param ipAddress
* @throws Exception
*/
public static boolean ping(String ipAddress) throws Exception {
int timeOut = 3000; // 超时应该在3钞以上
boolean status = ByName(ipAddress).isReachable(timeOut); // 当返回值是true时,说明host是可⽤的,false则不可。    return status;
}
/**
* 使⽤java调⽤cmd命令,这种⽅式最简单,可以把ping的过程显⽰在本地。ping出相应的格式
* @param url
* @throws Exception
*/
public static void ping1(String url) throws Exception {
String line = null;
// 获取主机名
URL transUrl = null;
String filePathName = "/sdcard/" + "/ping";
File commonFilePath = new File(filePathName);
if (!ists()) {
commonFilePath.mkdirs();
Log.w(TAG, "create path: " + commonFilePath);
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(new Date());
String file = "result" + date + ".txt";
pingFile = new File(commonFilePath,file);
try {
transUrl = new URL(url);
String hostName = Host();
Log.e(TAG, "hostName: " + hostName);
runtime = Runtime();
process = ("ping " + hostName);
BufferedReader buf = new BufferedReader(new InputStream()));
int k = 0;
while ((line = adLine()) != null) {
if (line.length() > 0 && line.indexOf("time=") > 0) {
String context = line.substring(line.indexOf("time="));
int index = context.indexOf("time=");
String str = context.substring(index + 5, index + 9);
Log.e(TAG, "time=: " + str);
String result =
new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()) + ", " + hostName + ", " + str + "\r\n";
Log.e(TAG, "result: " + result);
write(pingFile, result);
}
}
} catch (Exception ex) {
System.out.Message());
}
}
/**
* 使⽤java调⽤控制台的ping命令,这个⽐较可靠,还通⽤,使⽤起来⽅便:传⼊个ip,设置ping的次数和超时,就可以根据返回值来判断是否ping通。  */
mkdirs方法public static boolean ping2(String ipAddress, int pingTimes, int timeOut) {
BufferedReader in = null;
// 将要执⾏的ping命令,此命令是windows格式的命令
Runtime r = Runtime();
String pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
try {
// 执⾏命令并获取输出
System.out.println(pingCommand);
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
// 逐⾏检查输出,计算类似出现=23ms TTL=62字样的次数
in = new BufferedReader(new InputStream()));
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
}
// 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
return connectedCount == pingTimes;
} catch (Exception ex) {
ex.printStackTrace(); // 出现异常则返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 停⽌运⾏ping
*/
public static void killPing() {
if (process != null) {
process.destroy();
Log.e(TAG, "process: " + process);
}
}
public static void write(File file, String content) {
BufferedWriter out = null;
Log.e(TAG, "file: " + file);
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
Pattern pattern = Patternpile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
return 1;
}
return 0;
}
/*
* public static void main(String[] args) throws Exception { String ipAddress = "appdlssl.dbankcdn"; //
* System.out.println(ping(ipAddress)); ping02(); // System.out.println(ping(ipAddress, 5, 5000)); }
*/
}
总结
到此这篇关于Android中实现ping功能的多种⽅法详解的⽂章就介绍到这了,更多相关android ping 功能内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。