Maverick
Maverick

Reputation: 2760

How to ping an IP using a socket and send data through it?

How can I ping an IP address using a socket program and send data through it?

Upvotes: 4

Views: 33796

Answers (3)

SamDJava
SamDJava

Reputation: 267

Ping uses ICMP protocol that is not available in java. This can be a better way to ping a server in java is to :

       try{
        String s = null;
        List<String> commands = new ArrayList<String>();
        commands.add("ping");
        commands.add("192.168.2.154");
        ProcessBuilder processbuilder = new ProcessBuilder(commands);
        Process process = processbuilder.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
         System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null)
            {
              System.out.println(s);
            }

    }catch (Exception e) {
 System.out.println("This is sad ");

}

Also another way could be is to work with pure java sockets.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533520

Ping is a specific ICMP protocol. You cannot send ICMP packets in pure Java.

However, you can open a TCP Socket to a specific port and send it some data. There are millions of example of tutorials on how to do this.

I suggest you look at these

http://www.google.co.uk/search?q=java+socket+tutorial 6 million results

http://www.google.co.uk/search?q=java+socket+example 11.6 million results.

To send just one character you can do

Socket s = new Socket(hostname, port);
s.getOutputStream().write((byte) '\n');
int ch = s.getInputStream().read();
s.close();
if (ch == '\n') // its all good.

Upvotes: 7

Liv
Liv

Reputation: 6124

You can't do ping in Java -- ping works at ICMP level which works on top of IP, whereas Java offers support for UDP (which sits on top of IP) and TCP (again on top of IP). It's basically a different (higher level) protocol for which you will need your own (native) library written in order to gain access to the IP stack.

Upvotes: 8

Related Questions