Find Internet Protocol Address


The resolveip function returns either the name or address of an IP (internet protocol) host. If you pass resolveip a host name, it returns the IP address. If you pass resolveip an IP address, it returns the host name. The function uses the class, which enables you to find an IP address for a host name, or the host name 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 host name and IP address for the input argument. It displays either the host name 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 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 host name or an IP address. If getByName fails, the catch statement displays an error message.

    function resolveip(input)
    	address =;
    	error(sprintf('Unknown host %s.', input))
  2. Retrieve the host name and IP address.

    The example uses calls to the getHostName and getHostAddress accessor functions on the object, to obtain the host name and IP address, respectively. These two functions return objects of class java.lang.String; use the char function to convert them to character arrays.

    hostname = char(address.getHostName);
    ipaddress = char(address.getHostAddress);
  3. Display the host name or IP address.

    The example uses the MATLAB® strcmp function to compare the input argument to the resolved IP address. If it matches, MATLAB displays the host name for the internet address. If the input does not match, MATLAB displays the IP address.

    if strcmp(input,ipaddress)
    	disp(sprintf('Host name of %s is %s', input, hostname)) 
    	disp(sprintf('IP address of %s is %s', input, ipaddress))

Running the Example

Here is an example of calling the resolveip function with a host name.

resolveip ('')
IP address of is

Here is a call to the function with an IP address.

resolveip ('')
Host name of is
Was this topic helpful?