3
votes

I want to ping an IP via Java. When I ping from command line and track the network packages I see ICMP requests. When I ping from my application and track the network packages I see TCP requests at port 7.

I've checked the documentation of InetAddress.isReachable():

Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible.

A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

I can run sudo needed commands with the user that I run my Java application.

Which privilege should be obtained for my purpose? What should I check?

PS: I've asked this question at stackoverflow.com because of it is more related to Java problem(which Java source code requires to run) than a system problem.

1
@maksimov that link says that: (ICMP) usually requires administrative (root) rights but it is not my case? - kamaci
This seems not a duplicate of java code to ping an IP address because it asks about a specific detail - the privilege mentioned in the documentation - whereas the other question is asking a more general question - SpaceTrucker
Does "requires root rights" not answer your question "which privilege?" - maksimov
@maksimov no it is not. I want to learn what are the privileges mentioned in the documentation. - kamaci
@maksimov Why? You are correct. 'Root privilege' is the answer to the question. - user207421

1 Answers

1
votes

Are you asking about Linux or about Java? - Obviously, the JVM process running your program will need to have all the Linux privileges required to open a "raw" ICMP socket, just as any other process.

For one implementation see e.g. Java_java_net_Inet4AddressImpl_isReachable0 where it basically just boils down to:

/*
 * Let's try to create a RAW socket to send ICMP packets
 * This usually requires "root" privileges, so it's likely to fail.
 */
 fd = JVM_Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
 if (fd != -1) {
    /*
     * It didn't fail, so we can use ICMP_ECHO requests.
     */
     return ping4(env, fd, &him, timeout, netif, ttl);
 }

 /*
  * Can't create a raw socket, so let's try a TCP socket
  */
 ...