Example usage for java.net InetAddress getHostAddress

List of usage examples for java.net InetAddress getHostAddress

Introduction

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

Prototype

public String getHostAddress() 

Source Link

Document

Returns the IP address string in textual presentation.

Usage

From source file:com.linkedin.urls.HostNormalizer.java

private void normalizeHost() {
    if (StringUtils.isEmpty(_host)) {
        return;//from   ww w .  j a  v a2  s. c  o  m
    }

    String host;
    try {
        //replace high unicode characters
        host = IDN.toASCII(_host);
    } catch (IllegalArgumentException ex) {
        //occurs when the url is invalid. Just return
        return;
    }

    host = host.toLowerCase();
    host = UrlUtil.decode(host);

    _bytes = tryDecodeHostToIp(host);

    if (_bytes != null) {
        InetAddress address;
        try {
            address = InetAddress.getByAddress(_bytes);
            String ipAddress = address.getHostAddress();
            if (address instanceof Inet6Address) {
                host = "[" + ipAddress + "]";
            } else {
                host = ipAddress;
            }
        } catch (UnknownHostException e) {
            return;
        }
    }

    if (StringUtils.isEmpty(host)) {
        return;
    }

    host = UrlUtil.removeExtraDots(host);

    _normalizedHost = UrlUtil.encode(host).replace("\\x", "%");
}

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

/**
 * SMTPS????????//from  www. j av a  2 s  .  co  m
 * 
 * @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:edu.vt.middleware.gator.log4j.JdbcConfigurator.java

/**
 * Gets first project to which the host possessing the given IP address is a
 * member.//from   ww  w.  ja  v a  2s.c  o m
 *
 * @param  addr  IP address.
 *
 * @return  First project to which the client at the given IP address is a
 * member.
 *
 * @throws  UnauthorizedClientException  If given client is not a member of
 * any projects.
 */
private ProjectConfig getProject(final InetAddress addr) throws UnauthorizedClientException {
    final Set<ProjectConfig> projects = new HashSet<ProjectConfig>();

    // Add projects that contain the given client by host or IP address
    projects.addAll(configManager.findProjectsByClientName(addr.getHostAddress()));
    projects.addAll(configManager.findProjectsByClientName(addr.getHostName()));
    if (projects.size() > 0) {
        return projects.iterator().next();
    } else {
        throw new UnauthorizedClientException(addr,
                String.format("%s not registered with any projects.", addr));
    }
}

From source file:org.callimachusproject.server.AccessLog.java

private String getClientAddress(HttpContext context) {
    if (context == null)
        return null;
    HttpConnection con = HttpCoreContext.adapt(context).getConnection();
    if (con instanceof HttpInetConnection) {
        InetAddress remoteAddress = ((HttpInetConnection) con).getRemoteAddress();
        if (remoteAddress != null)
            return remoteAddress.getHostAddress();
    }/*from   www.  j a  v a2  s.c o  m*/
    return null;
}

From source file:de.micromata.mgc.application.webserver.config.JettyConfigTabController.java

private List<String> getListenHosts() {
    List<String> ret = new ArrayList<>();
    try {/*ww w.ja v  a2s.  co m*/
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            if (n.isUp() == false) {
                continue;
            }
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                //          ret.add(i.getHostName());
                ret.add(i.getHostAddress());
                //          System.out.println(i.getHostAddress());
            }
        }
    } catch (Exception ex) {
        ValMessage vm = new ValMessage(ValState.Error, "");
        vm.setMessage("Error retriving hosts: " + ex.getMessage());
        addToFeedback(vm);
    }
    return ret;
}

From source file:BaseProperties.java

/**
 * Set <code>InetAddress</code>.
 *//*  w w w  .  j  a  v a  2 s .c o m*/
public void setInetAddress(final String key, final InetAddress val) {
    setProperty(key, val.getHostAddress());
}

From source file:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Listener.java

/**
 * Handle Job. Implementation of ThreadPool.handle(), calls
 * handleConnection./*  w  ww .  j a  va 2 s .  c o  m*/
 * 
 * @param socket
 *            A Connection.
 */
public void handleConnection(Socket socket) throws IOException {
    // Check acceptable remote servers
    if (_remoteServers != null && _remoteServers.length > 0) {
        boolean match = false;
        InetAddress inetAddress = socket.getInetAddress();
        String hostAddr = inetAddress.getHostAddress();
        String hostName = inetAddress.getHostName();
        for (int i = 0; i < _remoteServers.length; i++) {
            if (hostName.equals(_remoteServers[i]) || hostAddr.equals(_remoteServers[i])) {
                match = true;
                break;
            }
        }
        if (!match) {
            log.warn("AJP13 Connection from un-approved host: " + inetAddress);
            return;
        }
    }

    // Handle the connection
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(getMaxIdleTimeMs());
    AJP13Connection connection = createConnection(socket);
    try {
        connection.handle();
    } finally {
        connection.destroy();
    }
}

From source file:brooklyn.location.basic.WinRmMachineLocation.java

@Override
public Set<String> getPublicAddresses() {
    InetAddress address = getAddress();
    return (address == null) ? ImmutableSet.<String>of() : ImmutableSet.of(address.getHostAddress());
}

From source file:com.buaa.cfs.nfs3.NfsExports.java

public AccessPrivilege getAccessPrivilege(InetAddress addr) {
    return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName());
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.cluster.impl.RelayClusterReceiverImpl.java

@Override
public void run() {
    byte[] receiveBuffer = new byte[UplinkReceiver.BUFFERSIZE];
    DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);

    while (this.run.get()) {
        try {/*ww  w  .  ja  v a2 s .  co m*/
            this.sock.receive(packet);

            InetAddress ip = packet.getAddress();
            int port = packet.getPort();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("received packet from RelayServer " + ip.getHostAddress() + ":" + port);
            }

            RelayServer me = this.relayServers.getMe();
            if (!(ip.equals(me.getIp()) && (port != this.relayClusterUdpPort))) {
                DatagramPacket msg = RelayClusterMessage.fromWireFormat(packet, this.reportOnce);
                if (msg != null) {
                    RelayServer rs = this.relayServers.getOrAdd(ip, port);
                    boolean packetCausedUpdate = this.packetHandler.processPacket(rs, msg);
                    if (this.relayClusterForwarding && packetCausedUpdate) {
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug(
                                    "forwarding packet from RelayServer " + ip.getHostAddress() + ":" + port);
                        }
                        this.relayClusterSender.addPacket(rs, msg);
                    }
                } else {
                    this.logger.error("Could not convert RelayClusterMessage from wire format");
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("skipping packet from RelayServer " + ip.getHostAddress() + ":" + port
                            + " since the packet came from me");
                }
            }
        } catch (Exception e) {
            if (!SocketException.class.equals(e.getClass())) {
                e.printStackTrace();
            }
        }
    }

    if (this.sock != null) {
        this.sock.close();
        this.sock = null;
    }
}