Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

In this page you can find the example usage for java.net InetAddress getByName.

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:com.alibaba.jstorm.utils.NetWorkUtils.java

public static String host2Ip(String host) {
    InetAddress address = null;//from w  w  w  . ja va  2  s . c o  m
    try {
        address = InetAddress.getByName(host);
    } catch (UnknownHostException e) {
        LOG.warn("NetWorkUtil can't transfer hostname(" + host + ") to ip, return hostname", e);
        return host;
    }
    return address.getHostAddress();
}

From source file:com.ok2c.lightmtp.util.InetAddressRangeParser.java

public InetAddressRange parse(final CharArrayBuffer buffer, final ParserCursor cursor, final char[] delimiters)
        throws ParseException, UnknownHostException {

    Args.notNull(buffer, "Char array buffer");
    Args.notNull(cursor, "Parser cursor");

    int pos = cursor.getPos();
    int indexFrom = cursor.getPos();
    int indexTo = cursor.getUpperBound();

    while (pos < indexTo) {
        char ch = buffer.charAt(pos);
        if (ch == '/') {
            break;
        }//from  w w  w .  j ava2 s. c  o m
        if (isOneOf(ch, delimiters)) {
            break;
        }
        pos++;
    }

    InetAddress address = InetAddress.getByName(buffer.substringTrimmed(indexFrom, pos));
    int mask = 0;

    if (pos < indexTo && buffer.charAt(pos) == '/') {
        pos++;
        indexFrom = pos;
        while (pos < indexTo) {
            char ch = buffer.charAt(pos);
            if (isOneOf(ch, delimiters)) {
                break;
            }
            pos++;
        }
        try {
            mask = Integer.parseInt(buffer.substringTrimmed(indexFrom, pos));
            if (mask < 0) {
                throw new ParseException("Negative range mask", indexFrom);
            }
        } catch (NumberFormatException ex) {
            throw new ParseException("Invalid range mask", indexFrom);
        }
    }
    cursor.updatePos(pos);
    return new InetAddressRange(address, mask);
}

From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java

/**
 * FTP????????//from   w  w w.  j  a  v  a  2s.c  o m
 * 
 * @param addressText
 * @return FTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        FTPClient client = new FTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (FTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(FTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:org.thoughtcrime.securesms.mms.MmsConnection.java

protected static boolean checkRouteToHost(Context context, String host, boolean usingMmsRadio)
        throws IOException {
    InetAddress inetAddress = InetAddress.getByName(host);
    if (!usingMmsRadio) {
        if (inetAddress.isSiteLocalAddress()) {
            throw new IOException("RFC1918 address in non-MMS radio situation!");
        }/*from   w  w  w  .j a v a  2s  . com*/
        Log.w(TAG, "returning vacuous success since MMS radio is not in use");
        return true;
    }
    byte[] ipAddressBytes = inetAddress.getAddress();
    if (ipAddressBytes == null || ipAddressBytes.length != 4) {
        Log.w(TAG, "returning vacuous success since android.net package doesn't support IPv6");
        return true;
    }

    Log.w(TAG, "Checking route to address: " + host + ", " + inetAddress.getHostAddress());
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    int ipAddress = Conversions.byteArrayToIntLittleEndian(ipAddressBytes, 0);
    boolean routeToHostObtained = manager.requestRouteToHost(MmsRadio.TYPE_MOBILE_MMS, ipAddress);
    Log.w(TAG, "requestRouteToHost result: " + routeToHostObtained);
    return routeToHostObtained;
}

From source file:com.clustercontrol.port.protocol.ReachAddressSMTP.java

/**
 * SMTP????????//from   w  ww.  j  a v  a  2  s .c om
 * 
 * @param addressText
 * @return SMTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the SMTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        SMTPClient client = new SMTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (SMTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(SMTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage(), e);
        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:models.DeviceConfig.java

public byte[] toBytes() {
    try {/*from   www . ja  v a2  s  . com*/
        //Creamos el buffer para serializar
        /*ip + netmask + gateway + mac + port + id + serverIP*/
        byte[] reponseBuffer = new byte[4 + 4 + 4 + 6 + 2 /*+ 4*/ + 4];

        byte[] address;
        //Copio la IP
        address = InetAddress.getByName(this.ip).getAddress();
        reponseBuffer[0] = address[0];
        reponseBuffer[1] = address[1];
        reponseBuffer[2] = address[2];
        reponseBuffer[3] = address[3];

        //Copio la netmask
        address = InetAddress.getByName(this.netmask).getAddress();
        reponseBuffer[4] = address[0];
        reponseBuffer[5] = address[1];
        reponseBuffer[6] = address[2];
        reponseBuffer[7] = address[3];

        //Copio el gateway
        address = InetAddress.getByName(this.gateway).getAddress();
        reponseBuffer[8] = address[0];
        reponseBuffer[9] = address[1];
        reponseBuffer[10] = address[2];
        reponseBuffer[11] = address[3];

        //Copio la mac
        reponseBuffer[12] = mac[0];
        reponseBuffer[13] = mac[1];
        reponseBuffer[14] = mac[2];
        reponseBuffer[15] = mac[3];
        reponseBuffer[16] = mac[4];
        reponseBuffer[17] = mac[5];

        //Copio el puerto
        reponseBuffer[18] = (byte) (this.port & 0xFF);
        reponseBuffer[19] = (byte) ((this.port >> 8) & 0xFF);

        //Copio el serverIP
        address = InetAddress.getByName(this.serverIP).getAddress();
        reponseBuffer[20] = address[0];
        reponseBuffer[21] = address[1];
        reponseBuffer[22] = address[2];
        reponseBuffer[23] = address[3];

        return reponseBuffer;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressNTP.java

/**
 * NTP????????/*from  ww w.j  a v  a2 s  . co m*/
 * 
 * @param addressText
 * @return NTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the NTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        NTPUDPClient client = new NTPUDPClient();
        TimeInfo time = null;

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                time = client.getTime(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                if (time != null) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }
                    result = new Date(time.getReturnTime()).toString();
                    retry = false;
                    isReachable = true;
                } else {
                    result = "failed to get time ";
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isOpen()) {
                    client.close();
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(NTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressSMTPS.java

/**
 * SMTPS????????/*from   www  .j av  a  2 s  . c om*/
 * 
 * @param addressText
 * @return SMTPS
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the SMTPS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        SMTPSClient client = new SMTPSClient(true);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (SMTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(SMTPS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage(), e);

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.clustercontrol.infra.util.WinRs.java

public WinRs(String host, int port, String protocol, String username, String password) {
    this.username = username;
    this.password = password;

    try {/*from w ww .j  av  a 2  s . com*/
        if (InetAddress.getByName(host) instanceof Inet6Address) {
            if (!"https".equals(protocol)) {
                url = String.format("http://[%s]:%d/wsman", host, port);
            } else {
                url = String.format("https://[%s]:%d/wsman", host, port);
            }
        } else {
            if (!"https".equals(protocol)) {
                url = String.format("http://%s:%d/wsman", host, port);
            } else {
                url = String.format("https://%s:%d/wsman", host, port);
            }
        }
    } catch (UnknownHostException e) {
        m_log.warn("UnknownException " + e.getMessage(), e);
    }
}

From source file:com.kylinolap.common.util.HadoopUtil.java

/**
 * e.g. "hbase:kylin-local.corp.ebay.com:2181:/hbase-unsecure"
 *//*from ww w .j  ava 2 s. c o  m*/
public static Configuration newHBaseConfiguration(String url) {
    Configuration conf = HBaseConfiguration.create();
    if (StringUtils.isEmpty(url))
        return conf;

    // chop off "hbase:"
    if (url.startsWith("hbase:") == false)
        throw new IllegalArgumentException("hbase url must start with 'hbase:' -- " + url);

    url = StringUtils.substringAfter(url, "hbase:");
    if (StringUtils.isEmpty(url))
        return conf;

    // case of "hbase:domain.com:2181:/hbase-unsecure"
    Pattern urlPattern = Pattern.compile("([\\w\\d\\-.]+)[:](\\d+)(?:[:](.*))?");
    Matcher m = urlPattern.matcher(url);
    if (m.matches() == false)
        throw new IllegalArgumentException("HBase URL '" + url + "' is invalid, expected url is like '"
                + "hbase:domain.com:2181:/hbase-unsecure" + "'");

    logger.debug("Creating hbase conf by parsing -- " + url);

    String quorum = m.group(1);
    try {
        InetAddress.getByName(quorum);
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Zookeeper quorum is invalid: " + quorum + "; urlString=" + url, e);
    }
    conf.set(HConstants.ZOOKEEPER_QUORUM, quorum);

    String port = m.group(2);
    conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, port);

    String znodePath = m.group(3) == null ? "" : m.group(3);
    if (StringUtils.isEmpty(znodePath) == false)
        conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, znodePath);

    // reduce rpc retry
    conf.set(HConstants.HBASE_CLIENT_PAUSE, "3000");
    conf.set(HConstants.HBASE_CLIENT_RETRIES_NUMBER, "5");
    conf.set(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, "60000");
    // conf.set(ScannerCallable.LOG_SCANNER_ACTIVITY, "true");

    return conf;
}