• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1750
  • Last Modified:

ICMP/PING

How can I program a PING command under Java. I don't want to  create daemons on each host but simply use their TCP/IP stack to respond to a ping. Others ideas would be welcome.
0
mido
Asked:
mido
1 Solution
 
jpk041897Commented:
Java does not support Raw packets, only UDP (SOCK_DGRAM)  and TCP (SOCK_STREAM), so ICMP is not possible

Additionaly, several platforms (including Win95 and NT) implementation of the TCP/IP don't even support raw sockets.Add to that that many UNIX hosts have disabled Ping do to ICMP attacks and the situation looks bad.

Fortunatley there is a work arround attributed to Qusay H. Mahmoud in the March issue of Java Cats (http://www.javacats.com/US/)

Its based on sending a TCP or UDP packet to the hosts echo port (port 7). If the connection cannot be establishd it is considered unreachable, otherwise its considered found. (It has the added advantage that it doesn't even have to send data).

The folling is Mahmoud's Java Ping class:


/*
 *  Program: ping.java
 *  @author: Qusay H. Mahmoud
 * @version: Nov 2, 1996
 */

import java.io.*;
import java.net.*;

public class ping {
    public final static int ECHO_PORT = 7;
    public static void main(String argv[]) {
        if (argv.length != 1) {
          System.out.println("Usage: java ping hostname");
          System.exit(0);
        }
        if (alive(argv[0])) {
          System.out.println(argv[0] + " is alive");
        } else {
         System.out.println("No response from " + argv[0] +". Host is down or does not exist");
        }
    }
 
    public static boolean alive(String host) {
        Socket pingSocket = null;
        try {
            pingSocket = new Socket(host, ECHO_PORT);
        } catch (UnknownHostException e) {
            System.err.println("UnknownHostException: " +e);
        } catch (IOException io) {
            System.out.println("IOException: " + io);
        }
        if (pingSocket != null) {
           try {
              pingSocket.close();
           } catch (IOException e) {
                System.err.println("IOException: " + e);
           }
           return true;
        } else {
           return false;
        }
    }
}

Hope this solves your problem.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now