4

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

Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
Maverick
  • 2,738
  • 24
  • 91
  • 157
  • 1
    Have you looked at [this question](http://stackoverflow.com/questions/2448666/how-to-do-a-true-java-ping-from-windows)? – MarcoS May 05 '11 at 12:12

3 Answers3

8

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.

Liv
  • 6,006
  • 1
  • 22
  • 29
7

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.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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.

SamDJava
  • 267
  • 3
  • 13
  • Make up your mind. Either ping is not available in Java or you can do it with pure Java sockets. Not both at the same time. – user207421 Jul 25 '14 at 12:41
  • There is no direct API that can ping another system. By using processBuilder we invoke system processes. To use pure java component that would not take help of any other system process , we need to use Sockets. – SamDJava Jul 28 '14 at 04:42