Pinging computer by name in Java

偶尔善良 提交于 2019-12-10 14:54:56

问题


I am in the process of writing a simple program that extracts computer names from MySQL Database then stores those names into a String array list (this part works fine). After that I wrote a class and a method that takes a String as a parameter (which will be the computer name) and tries to ping it. Here is the code for that class:

public class Ping 
{
public void pingHost(String hostName)
{   
    try
    {
        InetAddress inet = InetAddress.getByName(hostName);
        boolean status = inet.isReachable(5000);
        if (status)
        {
            System.out.println(inet.getHostName() + " Host Reached\t" + inet.getHostAddress());
        }
        else
        {
            System.out.println(inet.getHostName() + " Host Unreachable");
        }

    }
    catch (UnknownHostException e)
    {
        System.err.println(e.getMessage() + " Can't Reach Host");
    }
    catch (IOException e)
    {
        System.err.println(e.getMessage() + " Error in reaching the Host");
    }
}

The problem is that I keep getting UnknownHostException thrown for most computers even if I can ping them manually or if I hard code the computer name as the "hostName".

Here is what my main looks like:

public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException 
{
    ArrayList <String> list = new ArrayList<String>();  
    MySQLConnect myConnection = new MySQLConnect();
    myConnection.importData(list);
    Ping pingComputer = new Ping();
    pingComputer.pingHost(list.get(87));            
}

Right now I'm just trying to experiment with one computer which is throwing UnknownHostException but can be pinged manually. Anyone have any idea why this is happening?

EDIT...

Just to explain this a little bit more. For example in main, if I pass these parameters to pingHost:

pingComputer.pingHost("ROOM-1234");

It pings fine and returns correct host name/address. But list.get(87) returns same host name "ROOM-1234" but throws UnknownHostException? This has got me really confused and not sure why its not working.

EDIT

Wow finally figured it out. Reason ping was working when I was passing the string directly like so "ROOM-1234", was because there were no white spaces and getting is from array like so list.get(87) returned same thing but when I checked charLength, it returned a different value :) So I just ended up using trim to get rid of white spaces and now itworks great.

pingComputer.pingHost(list.get(87).trim());

Thanks for all the suggestions!


回答1:


Dear Actually the code you are using is to check whether the host is reachable or not.

Use following class to ping windows pc use ping method but for other than windows pc use isreachable.

package com.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Ping {

    public Boolean IsReachable(String ipaddress) {
        try {            
            final InetAddress host = InetAddress.getByName(ipaddress);

            try {
                return host.isReachable(3000);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Boolean ping(String ipaddress) {
        Runtime runtime = Runtime.getRuntime();
        String cmds = "ping " + ipaddress;
        System.out.println(cmds);
        Process proc;

        try {
            proc = runtime.exec(cmds);
            proc.getOutputStream().close();
            InputStream inputstream = proc.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            String line;

            while ((line = bufferedreader.readLine()) != null) {
                if (line.contains("Reply from " + ipaddress + ":")) {
                    return true;
                }
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
        return false;
    }
}

And use as below code

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    MySQLConnect myConnection = new MySQLConnect();
    myConnection.importData(list);
    Ping ping = new Ping();

    if (ping.ping(list.get(87)) {
        System.out.prinln("Online / Host is reachable");
    } else {
        System.out.prinln("Offline /Host is unreachable");
    }
}

But I would suggest ping by ip address is better than pinging with computer name.



来源:https://stackoverflow.com/questions/12059932/pinging-computer-by-name-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!