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.netflix.priam.resources.CassandraAdmin.java

@GET
@Path("/netstats")
public Response netstats(@QueryParam("host") String hostname)
        throws IOException, ExecutionException, InterruptedException, JSONException {
    JMXNodeTool nodetool = null;//from   ww  w.j a  va 2 s.c o  m
    try {
        nodetool = JMXNodeTool.instance(config);
    } catch (JMXConnectionException e) {
        return Response.status(503).entity("JMXConnectionException").build();
    }
    JSONObject rootObj = new JSONObject();
    rootObj.put("mode", nodetool.getOperationMode());
    final InetAddress addr = (hostname == null) ? null : InetAddress.getByName(hostname);
    Set<InetAddress> hosts = addr == null ? nodetool.getStreamDestinations() : new HashSet<InetAddress>() {
        {
            add(addr);
        }
    };
    if (hosts.size() == 0)
        rootObj.put("sending", "Not sending any streams.");

    JSONObject hostSendStats = new JSONObject();
    for (InetAddress host : hosts) {
        try {
            List<String> files = nodetool.getFilesDestinedFor(host);
            if (files.size() > 0) {
                JSONArray fObj = new JSONArray();
                for (String file : files)
                    fObj.put(file);
                hostSendStats.put(host.getHostAddress(), fObj);
            }
        } catch (IOException ex) {
            hostSendStats.put(host.getHostAddress(), "Error retrieving file data");
        }
    }

    rootObj.put("hosts sending", hostSendStats);
    hosts = addr == null ? nodetool.getStreamSources() : new HashSet<InetAddress>() {
        {
            add(addr);
        }
    };
    if (hosts.size() == 0)
        rootObj.put("receiving", "Not receiving any streams.");

    JSONObject hostRecvStats = new JSONObject();
    for (InetAddress host : hosts) {
        try {
            List<String> files = nodetool.getIncomingFiles(host);
            if (files.size() > 0) {
                JSONArray fObj = new JSONArray();
                for (String file : files)
                    fObj.put(file);
                hostRecvStats.put(host.getHostAddress(), fObj);
            }
        } catch (IOException ex) {
            hostRecvStats.put(host.getHostAddress(), "Error retrieving file data");
        }
    }
    rootObj.put("hosts receiving", hostRecvStats);

    MessagingServiceMBean ms = nodetool.msProxy;
    int pending;
    long completed;
    pending = 0;
    for (int n : ms.getCommandPendingTasks().values())
        pending += n;
    completed = 0;
    for (long n : ms.getCommandCompletedTasks().values())
        completed += n;
    JSONObject cObj = new JSONObject();
    cObj.put("active", "n/a");
    cObj.put("pending", pending);
    cObj.put("completed", completed);
    rootObj.put("commands", cObj);

    pending = 0;
    for (int n : ms.getResponsePendingTasks().values())
        pending += n;
    completed = 0;
    for (long n : ms.getResponseCompletedTasks().values())
        completed += n;
    JSONObject rObj = new JSONObject();
    rObj.put("active", "n/a");
    rObj.put("pending", pending);
    rObj.put("completed", completed);
    rootObj.put("responses", rObj);
    return Response.ok(rootObj, MediaType.APPLICATION_JSON).build();
}

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

public String openActiveMode() throws IOException {
    InetAddress addr = NetUtils.getMachineAddress(true);
    String addrStr = addr != null ? addr.getHostAddress() : "127.0.0.1";
    ServerSocket sock = ServerSocketFactory.getDefault().createServerSocket(0, 1, addr);
    sock.setSoTimeout(10000);//  w  w w.  j a  va  2  s.  c  o  m

    Pattern pattern = Pattern.compile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$");
    Matcher matcher = pattern.matcher(addrStr);
    if (!matcher.matches()) {
        throw new IOException("Invalid address: " + addrStr);
    }
    int p1 = (sock.getLocalPort() >>> FtpConstants.BYTE_LENGTH) & FtpConstants.BYTE_MASK;
    int p2 = sock.getLocalPort() & FtpConstants.BYTE_MASK;

    StringBuffer sb = new StringBuffer();
    sb.append("PORT ");
    sb.append(matcher.group(1));
    sb.append(",");
    sb.append(matcher.group(2));
    sb.append(",");
    sb.append(matcher.group(3));
    sb.append(",");
    sb.append(matcher.group(4));
    sb.append(",");
    sb.append(p1);
    sb.append(",");
    sb.append(p2);

    resetDataSockets();
    activeModeServerSocket = sock;

    sendCommand(sb.toString());

    return getResponse();

}

From source file:com.maxmind.geoip2.WebServiceClient.java

private <T> T responseFor(String path, InetAddress ipAddress, Class<T> cls)
        throws GeoIp2Exception, IOException {
    GenericUrl uri = this.createUri(path, ipAddress);
    HttpResponse response = this.getResponse(uri);
    Long contentLength = response.getHeaders().getContentLength();

    if (contentLength == null || contentLength.intValue() <= 0) {
        throw new HttpException("Received a 200 response for " + uri + " but there was no message body.", 200,
                uri.toURL());/*from   w  w  w.j a  va2  s. c o  m*/
    }

    String body = WebServiceClient.getSuccessBody(response, uri);

    String ip = ipAddress == null ? null : ipAddress.getHostAddress();
    InjectableValues inject = new JsonInjector(locales, ip);

    try {
        return mapper.readerFor(cls).with(inject).readValue(body);
    } catch (IOException e) {
        throw new GeoIp2Exception("Received a 200 response but not decode it as JSON: " + body, e);
    }
}

From source file:com.l2jfree.loginserver.manager.LoginManager.java

/**
 * @param user/*from   w  w  w.  j a v a 2 s.c om*/
 * @param address
 * @param hash
 * @return true if accounts was successfully created or false is AUTO_CREATE_ACCOUNTS = false or creation failed
 * @throws AccountModificationException
 */
private boolean handleAccountNotFound(String user, InetAddress address, byte[] hash)
        throws AccountModificationException {
    Accounts acc;
    if (Config.AUTO_CREATE_ACCOUNTS) {
        if ((user.length() >= 2) && (user.length() <= 14)) {
            acc = new Accounts(user, Base64.encodeBytes(hash), new BigDecimal(System.currentTimeMillis()), 0, 0,
                    1900, 1, 1, (address == null ? "null" : address.getHostAddress()));
            _service.addOrUpdateAccount(acc);

            _logLogin.info("Account created: " + user);
            _log.info("An account was newly created: " + user);
            Status.tryBroadcast("Account created for player " + user);

            return true;

        }
        _logLogin.warn("Invalid username creation/use attempt: " + user);
        return false;
    }
    _logLogin.warn("No such account exists: " + user);
    return false;
}

From source file:org.apache.synapse.transport.nhttp.ServerWorker.java

/**
 * Create an Axis2 message context for the given http request. The request may be in the
 * process of being streamed/*from   w w  w  . j a va2 s .c  o  m*/
 * @param request the http request to be used to create the corresponding Axis2 message context
 * @return the Axis2 message context created
 */
private MessageContext createMessageContext(HttpRequest request) {

    MessageContext msgContext = new MessageContext();
    msgContext.setMessageID(UIDGenerator.generateURNString());

    // There is a discrepency in what I thought, Axis2 spawns a new threads to
    // send a message if this is TRUE - and I want it to be the other way
    msgContext.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, Boolean.FALSE);
    msgContext.setConfigurationContext(cfgCtx);
    if ("https".equalsIgnoreCase(schemeName)) {
        msgContext.setTransportOut(cfgCtx.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTPS));
        msgContext.setTransportIn(cfgCtx.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTPS));
        msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTPS);

        SSLIOSession session = (SSLIOSession) (conn.getContext()).getAttribute(SSLIOSession.SESSION_KEY);
        //set SSL certificates to message context if SSLVerifyClient parameter is set
        if (session != null && msgContext.getTransportIn() != null
                && msgContext.getTransportIn().getParameter(NhttpConstants.SSL_VERIFY_CLIENT) != null) {
            try {
                msgContext.setProperty(NhttpConstants.SSL_CLIENT_AUTH_CERT_X509,
                        session.getSSLSession().getPeerCertificateChain());
            } catch (SSLPeerUnverifiedException e) {
                //Peer Certificate Chain may not be available always.(in case of verify client is optional)
                if (log.isTraceEnabled()) {
                    log.trace("Peer certificate chain is not available for MsgContext "
                            + msgContext.getMessageID());
                }
            }
        }
    } else {
        msgContext.setTransportOut(cfgCtx.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTP));
        msgContext.setTransportIn(cfgCtx.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTP));
        msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP);
    }
    msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, this);
    // the following statement causes the soap session services to be failing - ruwan        
    // msgContext.setServiceGroupContextId(UUIDGenerator.getUUID());
    msgContext.setServerSide(true);
    msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getRequestLine().getUri());

    // http transport header names are case insensitive 
    Map<String, String> headers = new TreeMap<String, String>(new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });

    for (Header header : request.getAllHeaders()) {

        String headerName = header.getName();

        // if this header is already added
        if (headers.containsKey(headerName)) {
            /* this is a multi-value header */
            // generate the key
            String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
            // get the old value
            String oldValue = headers.get(headerName);
            // adds additional values to a list in a property of message context
            Map map;
            if (msgContext.getProperty(key) != null) {
                map = (Map) msgContext.getProperty(key);
                map.put(headerName, oldValue);
            } else {
                map = new MultiValueMap();
                map.put(headerName, oldValue);
                // set as a property in message context
                msgContext.setProperty(key, map);
            }

        }
        headers.put(header.getName(), header.getValue());
    }
    msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headers);

    // find the remote party IP address and set it to the message context
    if (conn instanceof HttpInetConnection) {
        HttpContext httpContext = conn.getContext();
        HttpInetConnection inetConn = (HttpInetConnection) conn;
        InetAddress remoteAddr = inetConn.getRemoteAddress();
        if (remoteAddr != null) {
            httpContext.setAttribute(NhttpConstants.CLIENT_REMOTE_ADDR, remoteAddr);
            httpContext.setAttribute(NhttpConstants.CLIENT_REMOTE_PORT, inetConn.getRemotePort());
            msgContext.setProperty(MessageContext.REMOTE_ADDR, remoteAddr.getHostAddress());
            msgContext.setProperty(NhttpConstants.REMOTE_HOST, NhttpUtil.getHostName(remoteAddr));
            remoteAddress = remoteAddr.getHostAddress();
        }
    }

    msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL,
            new HttpCoreRequestResponseTransport(msgContext));

    msgContext.setProperty(ServerHandler.SERVER_CONNECTION_DEBUG,
            conn.getContext().getAttribute(ServerHandler.SERVER_CONNECTION_DEBUG));

    msgContext.setProperty(NhttpConstants.NHTTP_INPUT_STREAM, is);
    msgContext.setProperty(NhttpConstants.NHTTP_OUTPUT_STREAM, os);

    return msgContext;
}

From source file:com.limegroup.gnutella.RouterService.java

/**
 * Determines if you're connected to the given host.
 *//*from  w  w  w.  j a  v a2  s  .  c om*/
public static boolean isConnectedTo(InetAddress addr) {
    // ideally we would check download sockets too, but
    // because of the way ManagedDownloader is built, it isn't
    // too practical.
    // TODO: rewrite ManagedDownloader

    String host = addr.getHostAddress();
    return manager.isConnectedTo(host) || UDPMultiplexor.instance().isConnectedTo(addr)
            || uploadManager.isConnectedTo(addr); // ||
    // dloadManager.isConnectedTo(addr);
}

From source file:de.mangelow.throughput.NotificationService.java

private String getIPAddress() {

    try {//  w  ww. j  a v  a 2s. c  o m
        String ipv4;
        List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
        if (nilist.size() > 0) {
            for (NetworkInterface ni : nilist) {
                List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                if (ialist.size() > 0) {
                    for (InetAddress address : ialist) {
                        if (!address.isLoopbackAddress()
                                && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress())) {
                            return ipv4;
                        }
                    }
                }

            }
        }

    } catch (SocketException ex) {
        if (D)
            ex.printStackTrace();
    }

    return "";

}

From source file:Reflector.java

private int setSourceIP(String value) {
    // validate and set the source IP from the config file

    // call modeToAddress to validate IP address
    InetAddress inet = modeToAddress(value, SOURCE);
    if (inet == null)
        return -1;

    if (source != null) {
        if (source.getAddress() != null)
            System.err.println("Warning: overwriting src address " + source.getAddress().getHostAddress()
                    + " with " + inet.getHostAddress() + ".");
        source.setAddress(inet);//  w  w  w .j  a  v  a2  s . c o  m
    } else {
        source = new Address(inet);
    }

    return (0);
}