Como implementar seu próprio método InetAddress.isReachable (String address, int port, int timeout) em Java?
Publicados: 2020-10-06
Em Java, existem várias maneiras de verificar o ping e a verificação da porta. Você pode usar o comando ping do padrão do sistema, o utilitário InetAddress
do método nativo do Java, HttpURLConnection
e muito mais.
Na produção ou em seu ambiente de teste, se você deseja executar várias verificações de porta, digamos centenas de verificações ao mesmo tempo, às vezes o método InetAddress.isReachable()
não está obtendo a resposta correta.
Infect no meu caso, notei 100% de falha ao tentar me conectar ao www.google.com. Você tem alguma das perguntas abaixo?
- java – Por que InetAddress.isReachable retorna false, quando posso pingar o endereço IP?
- Como verificar se tenho conexão com a internet?
- Exemplos de código Java para java.net.InetAddress.isReachable()
- java verifique se o endereço IP está acessível
- Como testar se um sistema remoto é alcançável?
Siga este tutorial se quiser realizar a verificação de ping usando HttpURLConnection.openConnection()
Neste tutorial, abordaremos 2 maneiras diferentes de realizar a verificação de Ping:
- Método InetAddress.isReachable(timeout)
- O método
crunchifyAddressReachable(host, port, timeout)
do Crunchify que funciona 100% do tempo
Vamos começar:
- Crie a classe CrunchifyInetAddressIsReachable.java.
- Criaremos 2 métodos pingCheckbyInetAddressisReachable() e pingCheckbyCrunchifyisReachable() nos quais realizaremos acima de 2 testes diferentes.
Que método estamos usando crunchifyAddressReachable()?
Estamos usando java.net.Socket
em nossa implementação. A classe Socket implementa os soquetes do cliente. Com a ajuda do utilitário connect()
estamos obtendo 100% do resultado correto do tempo. Por favor, dê uma olhada no código abaixo para mais detalhes.
CrunchifyInetAddressIsReachable.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
package crunchify . com . tutorial ; import java . io . IOException ; import java . net . InetAddress ; import java . net . InetSocketAddress ; import java . net . Socket ; /** * @author Crunchify.com * Problem: Sometimes InetAddress.isReachable() gives false result. * We have implemented the same Reachable check using Socket. It works almost 100% of the time. * Comparison added. * Version: 1.1 * */ public class CrunchifyInetAddressIsReachable { static String host = "www.google.com" ; public static void main ( String [ ] args ) { // check ping using default Java Utility pingCheckbyInetAddressisReachable ( ) ; // check ping using modified Crunchify Utility pingCheckbyCrunchifyisReachable ( ) ; } private static void pingCheckbyInetAddressisReachable ( ) { try { InetAddress crunchifyAddr = InetAddress . getByName ( host ) ; boolean reachable = crunchifyAddr . isReachable ( 2000 ) ; if ( reachable ) { System . out . println ( "InetAddress.isReachable(timeout) Result ==> Ping successful for host: " + host ) ; } else { System . out . println ( "InetAddress.isReachable(timeout) Result ==> Ping failed for host: " + host ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } private static void pingCheckbyCrunchifyisReachable ( ) { try { crunchifyAddressReachable ( host , 80 , 2000 ) ; System . out . println ( "\nOverloaded isReachable(host, port, timeout) Result ==> Ping successful for host: " + host ) ; } catch ( Exception e ) { System . out . println ( "\nOverloaded isReachable(host, port, timeout) Result ==> Ping failed for host: " + host ) ; } } /* * Overriding default InetAddress.isReachable() method to add 2 more arguments port and timeout value * * Address: www.google.com * port: 80 or 443 * timeout: 2000 (in milliseconds) */ private static boolean crunchifyAddressReachable ( String address , int port , int timeout ) throws IOException { Socket crunchifySocket = new Socket ( ) ; try { // Connects this socket to the server with a specified timeout value. crunchifySocket . connect ( new InetSocketAddress ( address , port ) , timeout ) ; // Return true if connection successful return true ; } catch ( IOException exception ) { exception . printStackTrace ( ) ; // Return false if connection fails return false ; } finally { crunchifySocket . close ( ) ; } } } |
Depois de copiar o código para o ambiente Eclipse, basta executar como Java Application para ver o resultado abaixo.

Saída do console:
1 2 3 |
InetAddress . isReachable ( 2000 ) Result == > Ping failed for host : www . google . com Overloaded isReachable ( host , port , timeout ) Result == > Ping successful for host : www . google . com |