The InetAddress.getByAddress()
method is a static method in the java.net.InetAddress
class that returns an InetAddress
object given the raw IP address. The raw IP address is specified as a byte array.
Here is an example of how to use the InetAddress.getByAddress()
method:
import java.net.InetAddress; import java.net.UnknownHostException; public class InetAddressExample { public static void main(String[] args) { try { // Create a byte array for the IP address 192.168.0.1 byte[] ipAddress = {(byte) 192, (byte) 168, 0, 1}; // Get the InetAddress object for the IP address InetAddress address = InetAddress.getByAddress(ipAddress); // Print the hostname and IP address System.out.println("Hostname: " + address.getHostName()); System.out.println("IP address: " + address.getHostAddress()); } catch (UnknownHostException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Hostname: 192.168.0.1 IP address: 192.168.0.1
Note that the getByAddress()
method can throw a UnknownHostException
if the IP address is invalid or if a hostname could not be resolved for the given IP address. It is recommended to handle this exception by enclosing the call to getByAddress()
in a try-catch
block.