How to ping an IP using a socket and send data thr

2020-06-23 08:18发布

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

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-06-23 08:58

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-06-23 08:58

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.
查看更多
我想做一个坏孩纸
4楼-- · 2020-06-23 09:03

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.

查看更多
登录 后发表回答