新手提问,java中判断网络连接是否正常 急
如题,在java中,如何判定网络是否正常,比如,指定一个ip地址,判断是否能连接上。
大家最好给出源码,因为是个新手,如果是思路,还要再找资料,等我先完成任务再消化内容 谢谢
------解决方案--------------------public class Test
{
public static void main(String[] args)
{
String ip = "192.168.1.1 ";
//ip = "google.com ";
try {
Process p = Runtime.getRuntime().exec( "cmd /c ping -n 1 " + ip); //此处1变大可以增加精确度,但影响测试速度
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String temp = null;
StringBuffer strBuffer = new StringBuffer();
while ((temp = (in.readLine())) != null)
strBuffer.append(temp);
//System.out.println(strBuffer);
if (strBuffer.toString().matches( ".*\\(\\d?\\d% loss\\).* ")) {
System.out.println( "正常 ");
}
else {
System.out.println( "不正常 ");
}
} catch (
IOException e) {
e.printStackTrace();
}
}
}
------解决方案--------------------import java.net.*;
import java.io.*;
public class IPTest
{
public static void main(String[] args)throws IOException
{
try
{
InetAddress ad = InetAddress.getByName( "192.168.1.119 ");
boolean state = ad.isReachable(5000);//测试是否可以达到该地址
if(state)
System.out.println( "连接成功 " + ad.getHostAddress());
else
System.err.println( "
连接失败 ");
}
catch(
UnknownHostException e)
{
System.err.println( "连接失败 ");
}
}
}
实现尽最大努力试图到达主机,但防火墙和服务器配置可能阻塞请求,使其在某些特定的端口可以访问时处于不可到达状态。