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

梦想的初衷 提交于 2019-12-09 13:30:07

问题


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


回答1:


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.




回答2:


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.



回答3:


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.



来源:https://stackoverflow.com/questions/5897421/how-to-ping-an-ip-using-a-socket-and-send-data-through-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!