The only way I know is to send the package to some well-known host, known in the sense that you know that it will always work and start from the calling site.
However, for example, if you select a named host, ping may fail due to a DNS lookup failure.
I think you should not worry about this problem: if your program needs an Internet connection, it sends or receives data. Communication is not a continuous concept, like a river, but rather a road. So just use the Java standard to handle connection errors: IOExceptiions. When your program needs to send data, the core API will issue an IOE in case the network is down. If your program is expecting data, instead use a timeout or something similar to detect possible errors in the network stack and report this to the user.
source share