Domanda IOException in Java viene generata da isReachable

OliWan

Utente Bronze
15 Luglio 2022
20
15
0
23
Se una IOException in Java viene generata da isReachable, quale sarebbe un'azione appropriata da intraprendere e perché?

Immagino che la risposta sia che il programma dovrebbe terminare l'operazione e stampare il messaggio di sistema: l'host non è raggiungibile. Poiché isReachable lancia IOException significa che l'host non è raggiungibile. Ma non sono sicuro della risposta. Se potessi aiutarmi, te ne sarò molto grato.
Grazie mille
 
The method isReachable() does not throw IOException when the IP address, passed as an argument, is not reachable. This method throws IOException when there are Input/Output problems. For example, your network interface does not work correctly or is broken. isReachable() returns a boolean value: True if the host is reachable and False if it is not reachable. You should use a simple "if-then-else" to handle the case where the host is reachable/not reachable. After, put this structure in a controlled region (try-catch). You should do something like this:

Java:
package ipaddress;

import java.io.IOException;
import java.net.InetAddress;
import java.util.*;

public class Verify {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter an IP address:");
        String ipAddress = sc.nextLine();
        try {
            if (InetAddress.getByName(ipAddress).isReachable(1000)){
                System.out.println("The host is reachable");
            } else {
                System.out.println("The host is not reachable");
            }
        } catch (IOException ex){
            System.out.println("An error occurred " + ex.getMessage());
        }
    }
}
 
  • Mi piace
Reazioni: JunkCoder