Program Tip

IP 주소를 ping하는 방법

programtip 2020. 10. 26. 08:29
반응형

IP 주소를 ping하는 방법


이 코드 부분을 사용하여 Java에서 ip 주소를 ping하지만 localhost 만 ping하는 것이 성공하고 다른 호스트의 경우 프로그램이 호스트에 연결할 수 없다고 말합니다. 방화벽을 비활성화했지만 여전히이 문제가 있습니다.

public static void main(String[] args) throws UnknownHostException, IOException {
    String ipAddress = "127.0.0.1";
    InetAddress inet = InetAddress.getByName(ipAddress);

    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");

    ipAddress = "173.194.32.38";
    inet = InetAddress.getByName(ipAddress);

    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}

출력은 다음과 같습니다.

127.0.0.1
호스트에
Ping 요청을 보낼 수 있습니다. 173.194.32.38
호스트에 Ping 요청을 보낼 수 없습니다.


안타깝게도 Java에서 지원되지 않는 ICMP에 의존하므로 Java에서 단순히 ping을 수행 할 수 없습니다.

http://mindprod.com/jgloss/ping.html

대신 소켓 사용

도움이되기를 바랍니다.


InetAddress.isReachable()javadoc 에 따르면 :

".. 일반적인 구현에서는 권한을 얻을 수 있으면 ICMP ECHO REQUEST를 사용하고, 그렇지 않으면 대상 호스트의 포트 7 (Echo)에서 TCP 연결을 설정하려고합니다 ..".

옵션 # 1 (ICMP)에는 일반적으로 관리 (root)권한이 필요합니다 .


이 코드가 도움이 될 것이라고 생각합니다.

public class PingExample {
    public static void main(String[] args){
        try{
            InetAddress address = InetAddress.getByName("192.168.1.103");
            boolean reachable = address.isReachable(10000);

            System.out.println("Is host reachable? " + reachable);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

연결을 확인하십시오. 내 컴퓨터에서 두 IP 모두에 대해 REACHABLE을 인쇄합니다.

127.0.0.1
호스트에
Ping 요청을 보낼
수 있습니다. 173.194.32.38 호스트에 Ping 요청을 보낼 수 있습니다.

편집하다:

주소를 얻기 위해 getByAddress ()를 사용하도록 코드를 수정할 수 있습니다.

public static void main(String[] args) throws UnknownHostException, IOException {
    InetAddress inet;

    inet = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
    System.out.println("Sending Ping Request to " + inet);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");

    inet = InetAddress.getByAddress(new byte[] { (byte) 173, (byte) 194, 32, 38 });
    System.out.println("Sending Ping Request to " + inet);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}

getByName () 메서드는 컴퓨터에서 불가능할 수있는 일종의 역방향 DNS 조회를 시도 할 수 있으며 getByAddress ()는이를 우회 할 수 있습니다.


확실히 작동합니다

import java.io.*;
import java.util.*;

public class JavaPingExampleProgram
{

  public static void main(String args[]) 
  throws IOException
  {
    // create the ping command as a list of strings
    JavaPingExampleProgram ping = new JavaPingExampleProgram();
    List<String> commands = new ArrayList<String>();
    commands.add("ping");
    commands.add("-c");
    commands.add("5");
    commands.add("74.125.236.73");
    ping.doCommand(commands);
  }

  public void doCommand(List<String> command) 
  throws IOException
  {
    String s = null;

    ProcessBuilder pb = new ProcessBuilder(command);
    Process process = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    {
      System.out.println(s);
    }

    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
    {
      System.out.println(s);
    }
  }

}

이 방법을 사용하여 Windows 및 기타 플랫폼에서 호스트를 ping 할 수 있습니다.

private static boolean ping(String host) throws IOException, InterruptedException {
    boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");

    ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", host);
    Process proc = processBuilder.start();

    int returnVal = proc.waitFor();
    return returnVal == 0;
}


다른 사람이 제공 한 것 외에는 잘 작동하지만 인터넷이 느리거나 알 수없는 네트워크 문제가있는 경우 일부 코드가 작동하지 않는 경우도 있습니다 ( isReachable()). 그러나 아래에 언급 된이 코드는 Windows에 대한 명령 줄 핑 (cmd ping) 역할을하는 프로세스를 생성합니다. 모든 경우에서 작동하며 시도되고 테스트되었습니다.

코드 :-

public class JavaPingApp {

public static void runSystemCommand(String command) {

    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader inputStream = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

        String s = "";
        // reading output stream of the command
        while ((s = inputStream.readLine()) != null) {
            System.out.println(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    String ip = "stackoverflow.com"; //Any IP Address on your network / Web
    runSystemCommand("ping " + ip);
}
}

도움이 되었기를 바랍니다, 건배 !!!


Windows의 ICMP에 의존하지 않지만이 구현은 새로운 Duration API 와 잘 작동 합니다.

public static Duration ping(String host) {
    Instant startTime = Instant.now();
    try {
        InetAddress address = InetAddress.getByName(host);
        if (address.isReachable(1000)) {
            return Duration.between(startTime, Instant.now());
        }
    } catch (IOException e) {
        // Host not available, nothing to do here
    }
    return Duration.ofDays(1);
}

oracle-jdk를 사용하는 Linux에서 제출 된 OP 코드는 루트가 아닌 경우 포트 7을 사용하고 루트 인 경우 ICMP를 사용합니다. 문서에서 지정한대로 루트로 실행될 때 실제 ICMP 에코 요청을 수행합니다.

MS 컴퓨터에서 실행하는 경우 ICMP 동작을 얻으려면 관리자 권한으로 앱을 실행해야 할 수 있습니다.


여기에 IP 주소를 핑하는 방법입니다 Java작동해야 그 WindowsUnix시스템은 :

import org.apache.commons.lang3.SystemUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CommandLine
{
    /**
     * @param ipAddress The internet protocol address to ping
     * @return True if the address is responsive, false otherwise
     */
    public static boolean isReachable(String ipAddress) throws IOException
    {
        List<String> command = buildCommand(ipAddress);
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        try (BufferedReader standardOutput = new BufferedReader(new InputStreamReader(process.getInputStream())))
        {
            String outputLine;

            while ((outputLine = standardOutput.readLine()) != null)
            {
                // Picks up Windows and Unix unreachable hosts
                if (outputLine.toLowerCase().contains("destination host unreachable"))
                {
                    return false;
                }
            }
        }

        return true;
    }

    private static List<String> buildCommand(String ipAddress)
    {
        List<String> command = new ArrayList<>();
        command.add("ping");

        if (SystemUtils.IS_OS_WINDOWS)
        {
            command.add("-n");
        } else if (SystemUtils.IS_OS_UNIX)
        {
            command.add("-c");
        } else
        {
            throw new UnsupportedOperationException("Unsupported operating system");
        }

        command.add("1");
        command.add(ipAddress);

        return command;
    }
}

Apache Commons Lang종속성 에 추가 하십시오.


나는 이것이 이전 항목으로 대답 한 것을 알고 있지만,이 질문에 대한 다른 사람을 위해 나는 창에서 "ping"프로세스를 사용한 다음 출력을 스크러빙 할 필요가없는 방법을 찾았습니다.

내가 한 일은 JNA를 사용하여 Window의 IP 도우미 라이브러리를 호출하여 ICMP 에코를 수행했습니다.

내 비슷한 문제에 대한 내 답변 보기


InetAddress가 항상 올바른 값을 반환하는 것은 아닙니다. 로컬 호스트의 경우 성공하지만 다른 호스트의 경우 호스트에 연결할 수 없음을 나타냅니다. 아래와 같이 ping 명령을 사용해보십시오.

try {
    String cmd = "cmd /C ping -n 1 " + ip + " | find \"TTL\"";        
    Process myProcess = Runtime.getRuntime().exec(cmd);
    myProcess.waitFor();

    if(myProcess.exitValue() == 0) {

    return true;
    }
    else {
        return false;
    }
}
catch (Exception e) {
    e.printStackTrace();
    return false;
}

몇 가지 옵션을 시도했습니다.

  1. 자바 InetAddress

InetAddress.getByName(ipAddress), Windows의 네트워크가 몇 번 시도한 후 오작동하기 시작했습니다.

  1. Java HttpURLConnection

            URL siteURL = new URL(url);
            connection = (HttpURLConnection) siteURL.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(pingTime);
            connection.connect();
    
            code = connection.getResponseCode();
            if (code == 200) {
                code = 200;
            }.
    

This was reliable but a bit slow

  1. Windows Batch File

I finally settled to creating a batch file on my windows machine with the following contents: ping.exe -n %echoCount% %pingIp% Then I called the .bat file in my java code using

public int pingBat(Network network) {
ProcessBuilder pb = new ProcessBuilder(pingBatLocation);
Map<String, String> env = pb.environment();

env.put(
        "echoCount", noOfPings + "");
env.put(
        "pingIp", pingIp);
File outputFile = new File(outputFileLocation);
File errorFile = new File(errorFileLocation);

pb.redirectOutput(outputFile);

pb.redirectError(errorFile);

Process process;

try {
    process = pb.start();
    process.waitFor();
    String finalOutput = printFile(outputFile);
    if (finalOutput != null && finalOutput.toLowerCase().contains("reply from")) {
        return 200;
    } else {
        return 202;
    }
} catch (IOException e) {
    log.debug(e.getMessage());
    return 203;
} catch (InterruptedException e) {
    log.debug(e.getMessage());
    return 204;
}

}

This proved to be the fastest and most reliable way


This should work:

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

public class Pinger {

private static String keyWordTolookFor = "average";

public Pinger() {
    // TODO Auto-generated constructor stub
}


 public static void main(String[] args) {
 //Test the ping method on Windows.
 System.out.println(ping("192.168.0.1")); }


public String ping(String IP) {
    try {
        String line;
        Process p = Runtime.getRuntime().exec("ping -n 1 " + IP);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (((line = input.readLine()) != null)) {

            if (line.toLowerCase().indexOf(keyWordTolookFor.toLowerCase()) != -1) {

                String delims = "[ ]+";
                String[] tokens = line.split(delims);
                return tokens[tokens.length - 1];
            } 
        }

        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
    return "Offline";
}

}

참고URL : https://stackoverflow.com/questions/11506321/how-to-ping-an-ip-address

반응형