日期:2014-05-20  浏览次数:20609 次

java实现ping命令
如何用java编写程序实现发现某一网段内的活动主机

------解决方案--------------------
Java 1.5以下没有对ICMP协议的支持,需要用JNI或NIO来完成,可以Google一下。

如果用1.5以上版本,有一个简单的方法

Java code

String host = "192.168.1.181"
int timeOut = 3000;
boolean status = InetAddress.getByName(host).isReachable(timeOut);

------解决方案--------------------
Java code
public static void main( String[] args )
    {
        StringBuffer buf = new StringBuffer();
        String s = "";
        Process process;
        try
        {
            process = Runtime.getRuntime().exec( "cmd /c " + "ping 127.0.0.1" );
            BufferedReader br = new BufferedReader( new InputStreamReader(
            process.getInputStream() ) );
            while ( ( s = br.readLine() ) != null )
            {
                buf.append( s + "\r\n" );
            }

            process.waitFor();
            System.out.println( buf );
        } catch ( Exception ex )
        {
            ex.printStackTrace();
        }
    }

------解决方案--------------------
探讨
Java codepublic static void main( String[] args )
{
StringBuffer buf = new StringBuffer();
String s = "";
Process process;
try
{
process = Runtime.getRuntime().exec( "cmd /c " + "ping 127.0.0.1" );
BufferedReader br = new BufferedReader( new InputStreamReader(
process.getInputStream() ) );
while…

------解决方案--------------------
2楼的方法不推荐,因为是用runtime.exec来直接调用ping命令,系统平台改变时要改代码。

其次没有必要用java重新写ping,大多说人关心的是用java来检测远程主机是否可用。

我把这个写在blog里了。

http://blog.csdn.net/cgaolei/archive/2009/06/04/4240835.aspx
------解决方案--------------------
探讨
Java 1.5以下没有对ICMP协议的支持,需要用JNI或NIO来完成,可以Google一下。

如果用1.5以上版本,有一个简单的方法


Java code
String host = "192.168.1.181"
int timeOut = 3000;
boolean status = InetAddress.getByName(host).isReachable(timeOut);




InetAddress.isReachable()方法实现了ICMP,也就是Ping.(需要有一定的系统权限)

------解决方案--------------------
探讨
Java codepublic static void main( String[] args )
{
StringBuffer buf = new StringBuffer();
String s = "";
Process process;
try
{
process = Runtime.getRuntime().exec( "cmd /c " + "ping 127.0.0.1" );
BufferedReader br = new BufferedReader( new InputStreamReader(
process.getInputStream() ) );
while…

------解决方案--------------------
多谢11楼指教,的解没有注意到,因为只看到了API,没有看到底层实现。

请问你给出的C代码对应的java版本是多少?谢谢
------解决方案--------------------
完全不懂你们在说什么。虽然学过一点JAVA不过这东西实在太高深。深受打击
------解决方案--------------------
权威是正确的
------解决方案--------------------
探讨
多谢11楼指教,的解没有注意到,因为只看到了API,没有看到底层实现。

请问你给出的C代码对应的java版本是多少?谢谢