How to check the IP address through a socket and send data through it?

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

+3
source share
3 answers

You cannot ping in Java - ping works at the ICMP level, which works on top of IP, while Java offers support for UDP (which is on top of IP) and TCP (again on top of IP). This is basically a different (higher level) protocol, for which you will need your own (own) library written to gain access to the IP stack.

+8
source

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

TCP-Socket . , .

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

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

,

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

Ping uses ICMP, which is not available in java. This might be the best way to execute a ping server in java:

       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 ");

}

Another way could be working with pure Java sockets.

0
source

All Articles