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.sshtools.j2ssh.agent.SshAgentForwardingListener.java

SshAgentForwardingListener(String sessionId, ConnectionProtocol connection) {
    log.info("Forwarding agent started");
    this.sessionId = sessionId;
    this.connection = connection;
    port = selectPort();//from  w  w  w . j ava 2  s  .c om
    location = "localhost:" + String.valueOf(port);
    thread = new Thread(new Runnable() {
        public void run() {
            state.setValue(StartStopState.STARTED);

            try {
                server = new ServerSocket(port, 5, InetAddress.getByName("localhost"));

                //server.bind(new InetSocketAddress("localhost", port));
                Socket socket;

                while ((state.getValue() == StartStopState.STARTED) && ((socket = server.accept()) != null)) {
                    AgentSocketChannel channel = new AgentSocketChannel(true);
                    channel.bindSocket(socket);

                    if (!SshAgentForwardingListener.this.connection.openChannel(channel)) {
                        log.warn("Failed to open agent forwarding channel");
                    }
                }
            } catch (Exception e) {
                if (state.getValue() == StartStopState.STARTED) {
                    log.warn("Forwarding agent socket failed", e);
                }
            }

            state.setValue(StartStopState.STOPPED);
        }
    });
}

From source file:com.couchbase.client.core.config.DefaultPortInfo.java

/**
 * Creates a new {@link DefaultPortInfo}.
 *
 * Note that if the hostname is null (not provided by the server), it is explicitly set to null because otherwise
 * the loaded InetAddress would point to localhost.
 *
 * @param services the list of services mapping to ports.
 *//* w w w. j a  va  2s  .  c  o  m*/
@JsonCreator
public DefaultPortInfo(@JsonProperty("services") Map<String, Integer> services,
        @JsonProperty("hostname") String hostname) {
    ports = new HashMap<ServiceType, Integer>();
    sslPorts = new HashMap<ServiceType, Integer>();
    try {
        this.hostname = hostname == null ? null : InetAddress.getByName(hostname);
    } catch (UnknownHostException e) {
        throw new CouchbaseException("Could not analyze hostname from config.", e);
    }

    for (Map.Entry<String, Integer> entry : services.entrySet()) {
        String service = entry.getKey();
        int port = entry.getValue();
        if (service.equals("mgmt")) {
            ports.put(ServiceType.CONFIG, port);
        } else if (service.equals("capi")) {
            ports.put(ServiceType.VIEW, port);
        } else if (service.equals("kv")) {
            ports.put(ServiceType.BINARY, port);
        } else if (service.equals("kvSSL")) {
            sslPorts.put(ServiceType.BINARY, port);
        } else if (service.equals("capiSSL")) {
            sslPorts.put(ServiceType.VIEW, port);
        } else if (service.equals("mgmtSSL")) {
            sslPorts.put(ServiceType.CONFIG, port);
        } else if (service.equals("n1ql")) {
            ports.put(ServiceType.QUERY, port);
        } else if (service.equals("n1qlSSL")) {
            sslPorts.put(ServiceType.QUERY, port);
        }
    }
}

From source file:org.tamacat.httpd.filter.geoip.GeoIP2AccessControlFilter.java

protected String getCountry(String ip) throws AddressNotFoundException {
    try {// www  .  jav a 2  s . co m
        CountryResponse response = reader.country(InetAddress.getByName(ip));
        return response.getCountry().getIsoCode();
    } catch (Exception e) {
        throw new ForbiddenException(e);
    }
}

From source file:com.mobius.software.mqtt.performance.controller.net.ClientBootstrap.java

public static boolean available(String host, int port) {
    try (ServerSocket ss = new ServerSocket(port, 50, InetAddress.getByName(host))) {
        ss.setReuseAddress(true);/* w  ww  . j av  a  2 s .co  m*/
        return true;
    } catch (IOException e) {
    }

    return false;
}

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

/**
 * DNS????????// w  w  w  . j  a va2 s.c  o m
 *
 * @param addressText
 * @return DNS
 */
/*
 * (non-Javadoc)
 *
 * @see
 * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java.
 * lang.String)
 */
@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);
        String addressStr = address.getHostAddress();
        if (address instanceof Inet6Address) {
            addressStr = "[" + addressStr + "]";
        }

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

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo);
        props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout));
        props.put("com.sun.jndi.dns.timeout.retries", "1");

        InitialDirContext idctx = null;

        String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost");
        m_log.debug("The hostname from which to retrieve attributes is " + hostname);

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

                start = HinemosTime.currentTimeMillis();

                idctx = new InitialDirContext(props);
                Attributes attrs = idctx.getAttributes(hostname);

                end = HinemosTime.currentTimeMillis();

                bufferOrg.append("\n");
                NamingEnumeration<? extends Attribute> allAttr = attrs.getAll();
                while (allAttr.hasMore()) {
                    Attribute attr = allAttr.next();
                    bufferOrg.append("Attribute: " + attr.getID() + "\n");
                    NamingEnumeration<?> values = attr.getAll();
                    while (values.hasMore())
                        bufferOrg.append("Value: " + values.next() + "\n");
                }
                bufferOrg.append("\n");

                m_response = end - start;

                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = result + ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = result + ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = result + ("Response Time < 1ms");
                }

                retry = false;
                isReachable = true;

            } catch (NamingException e) {
                result = (e.getMessage() + "[NamingException]");
                retry = true;
                isReachable = false;
            } catch (Exception e) {
                result = (e.getMessage() + "[Exception]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                try {
                    if (idctx != null) {
                        idctx.close();
                    }
                } catch (NamingException 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 + "(DNS/" + 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.elasticgrid.model.internal.jibx.Conversion.java

public static InetAddress deserializeInetAddress(String address) throws UnknownHostException {
    if (StringUtils.isEmpty(address))
        return null;
    return InetAddress.getByName(address);
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

public static boolean isIPv4Address(String address) {
    if (address.isEmpty()) {
        return false;
    }/*  w  w w  . j  a  va2 s .  co m*/
    try {
        Object res = InetAddress.getByName(address);
        return (res.getClass().equals(Inet4Address.class));
    } catch (final UnknownHostException ex) {
        logger.error("Cannot get the host IP address. The captured address is: {}. Error: {}", address,
                ex.getMessage());
        return false;
    }
}

From source file:com.predic8.membrane.core.transport.http.Connection.java

public static Connection open(InetAddress host, int port, String localHost, SSLProvider sslProvider,
        ConnectionManager mgr, int connectTimeout) throws UnknownHostException, IOException {
    Connection con = new Connection(mgr);

    if (sslProvider != null) {
        if (isNullOrEmpty(localHost))
            con.socket = sslProvider.createSocket(host, port, connectTimeout);
        else/*from w  ww.j a  v  a 2 s. c o m*/
            con.socket = sslProvider.createSocket(host, port, InetAddress.getByName(localHost), 0,
                    connectTimeout);
    } else {
        if (isNullOrEmpty(localHost)) {
            con.socket = new Socket();
        } else {
            con.socket = new Socket();
            con.socket.bind(new InetSocketAddress(InetAddress.getByName(localHost), 0));
        }
        con.socket.connect(new InetSocketAddress(host, port), connectTimeout);
    }

    log.debug("Opened connection on localPort: " + con.socket.getLocalPort());
    //Creating output stream before input stream is suggested.
    con.out = new BufferedOutputStream(con.socket.getOutputStream(), 2048);
    con.in = new BufferedInputStream(con.socket.getInputStream(), 2048);

    return con;
}

From source file:com.jim.im.login.config.GatewayConfig.java

/**
 * geteway EntSystemManagerService bean/*from w w  w  .  ja  va 2  s .  com*/
 * @return
 * @throws UnknownHostException
 */
@Bean
public EntSystemManagerService entSystemManagerService() throws UnknownHostException {
    ProtocolRegister.registerProcotol(CommandIDs.vlsp_eaEntSystemManagerService.getuserstatusMethod, null,
            new EntSystemManagerService_getuserstatusRequest(),
            new EntSystemManagerService_getuserstatusResponse());

    EntSystemManagerService service = new EntSystemManagerService(InetAddress.getByName(gateway_ip),
            gateway_port);

    return service;
}

From source file:com.edmunds.etm.management.api.HostAddress.java

/**
 * Gets the host ip address./*from   w w  w . j  a v  a  2  s  . c o m*/
 *
 * @return host ip address
 */
public String getIpAddress() {
    if (ipAddress == null) {
        try {
            InetAddress addr = InetAddress.getByName(host);
            ipAddress = addr.getHostAddress();
        } catch (UnknownHostException e) {
            ipAddress = null;
        }
    }

    return ipAddress;
}