User`s manual

5 Calling Java from MATLAB
5-66
Example – Finding an Internet Protocol Address
The resolveip function returns either the name or address of an IP (internet
protocol) host. If you pass
resolveip a hostname, it returns the IP address. If
you pass
resolveip an IP address, it returns the hostname. The function uses
the Java API class
java.net.InetAddress, which enables you to find an IP
address for a hostname, or the hostname for a given IP address, without
making DNS calls.
resolveip calls a static method on the InetAddress class to obtain an
InetAddress object. Then, it calls accessor methods on the InetAddress object
to get the hostname and IP address for the input argument. It displays either
the hostname or the IP address, depending on the program input argument.
Description of resolveip
The major tasks performed by resolveip are:
1. Create an InetAddress Object
Instead of constructors, the java.net.InetAddress class has static methods
that return an instance of the class. The
try statement calls one of those
methods,
getByName, passing the input argument that the user has passed to
resolveip. The input argument can be either a hostname or an IP address. If
getByName fails, the catch statement displays an error message.
function resolveip(input)
try
address = java.net.InetAddress.getByName(input);
catch
error(sprintf('Unknown host %s.', input));
end
2. Retrieve the Hostname and IP Address
The example uses calls to the getHostName and getHostAddress accessor
functions on the
java.net.InetAddress object, to obtain the hostname and IP
address, respectively. These two functions return objects of class
java.lang.String, so we use the char function to convert them to character
arrays.
hostname = char(address.getHostName);
ipaddress = char(address.getHostAddress);