Java InetAddress from toInetAddress(String host)

Here you can find the source of toInetAddress(String host)

Description

Converts a hostname or IP address into a InetAddress.

License

Open Source License

Parameter

Parameter Description
host Hostname or IP address.

Return

InetAddress object. null if host is invalid.

Declaration

public static InetAddress toInetAddress(String host) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    /**//from w  ww  .  j a  v a  2s.c  om
     * Converts a hostname or IP address into a InetAddress.
     *
     * @param host Hostname or IP address.
     * @return InetAddress object.  <code>null</code> if host is invalid.
     */
    public static InetAddress toInetAddress(String host) {

        InetAddress addr = null;
        if (host.length() > 0) {
            try {
                addr = InetAddress.getByName(host);
                /*
                 * If the address is numeric, check if it's canonical host
                 * name is equal to it's host name.  This prevents the
                 * case where Java resolves 192.168.1 as 192.168.0.1, 
                 * hence creating a valid InetAddress when it shouldn't.
                 */
                int periodCount = 0;
                if (isMaybeIpAddress(host, periodCount)) {
                    String canHostNm = addr.getCanonicalHostName();
                    String hostNm = addr.getHostName();
                    if (!canHostNm.equals(hostNm)) {
                        addr = null; // Invalid address.
                    }
                }
            } catch (UnknownHostException e) {
                addr = null;
            } catch (SecurityException e) {
                addr = null;
            }
        }
        return addr;
    }

    /**
     * Checks whether a string might be an IP address instead of a host name.
     *
     * @param host String to check.
     * @param periodCount Populated with the number of periods encountered.
     * @return True if <I>host</I> is well formed (e.g. contains only
     * numbers and periods.
     */
    private static boolean isMaybeIpAddress(String host, int periodCount) {

        char[] hostChars = host.toCharArray();
        periodCount = 0;
        boolean addrIsIp = true;
        for (int i = 0; i < host.length(); i++) {
            if (!Character.isDigit(hostChars[i])) {
                if ((periodCount < 3) && (hostChars[i] == '.')) {
                    periodCount++;
                } else {
                    addrIsIp = false;
                    break;
                }
            }
        }
        return addrIsIp;
    }
}

Related

  1. intToInetAddress(int i)
  2. ip2Long(InetAddress ip)
  3. ipToBytesByInetAddress(String ip)
  4. ipToLong(InetAddress ip)
  5. long2InetAddress(long val)