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:edu.umass.cs.msocket.proxy.ProxyGnsPublisher.java

/**
 * Establish a connection with the GNS, register the proxy in the proxy group,
 * start a monitoring socket and register its IP in the GNS,
 * /*from  w  ww.ja va 2  s.  c  om*/
 * @throws Exception
 */
public void registerProxyInGns() throws Exception {
    logger.info("Looking for proxy " + proxyName + " GUID and certificates...");
    GuidEntry myGuid = KeyPairUtils.getGuidEntryFromPreferences(
            gnsCredentials.getGnsHost() + ":" + gnsCredentials.getGnsPort(), proxyName);

    final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
    if (myGuid == null) {
        logger.info("No keys found for proxy " + proxyName + ". Generating new GUID and keys");
        myGuid = gnsClient.guidCreate(gnsCredentials.getGuidEntry(), proxyName);
    }
    logger.info("Proxy has guid " + myGuid.getGuid());

    // Determine our IP
    String sIp = null;
    BufferedReader in;
    InetAddress addr;
    try {
        addr = ((InetSocketAddress) proxySocketAddres).getAddress();
        if (addr != null && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
                && !addr.isSiteLocalAddress())
            sIp = addr.getHostAddress();
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to resolve proxy address " + proxySocketAddres, e);
    }

    if (sIp == null) {
        logger.warning("Local proxy address (" + proxySocketAddres + ") does not seem to be a public address");
        try {
            logger.info("Determining local IP");
            // Determine our external IP address by contacting http://icanhazip.com
            URL whatismyip = new URL("http://icanhazip.com");
            in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
            sIp = in.readLine();
            in.close();
        } catch (Exception e) {
        }
    }

    ProxyInfo proxyInfo = new ProxyInfo(myGuid.getGuid(), proxyName, sIp);

    try {
        // Contact http://freegeoip.net/csv/[IP] to resolve IP address location
        URL locator = new URL("http://freegeoip.net/csv/" + sIp);
        in = new BufferedReader(new InputStreamReader(locator.openStream()));
        String csv = in.readLine();
        in.close();
        // Read location result
        StringTokenizer st = new StringTokenizer(csv, ",");
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read IP");
        st.nextToken(); // IP
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read country code");
        String countryCode = st.nextToken().replace("\"", "");
        proxyInfo.setCountryCode(countryCode);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read country name");
        String countryName = st.nextToken().replace("\"", "");
        proxyInfo.setCountryName(countryName);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read state code");
        String stateCode = st.nextToken().replace("\"", "");
        proxyInfo.setStateCode(stateCode);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read state name");
        String stateName = st.nextToken().replace("\"", "");
        proxyInfo.setStateName(stateName);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read city");
        String city = st.nextToken().replace("\"", "");
        proxyInfo.setCity(city);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read zip");
        String zip = st.nextToken().replace("\"", "");
        proxyInfo.setZipCode(zip);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read latitude");
        String latitudeStr = st.nextToken().replace("\"", "");
        double latitude = Double.parseDouble(latitudeStr);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read longitude");
        String longitudeStr = st.nextToken().replace("\"", "");
        double longitude = Double.parseDouble(longitudeStr);
        proxyInfo.setLatLong(new GlobalPosition(latitude, longitude, 0));
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to locate IP address " + e);
    }

    // Look for the group GUID
    String groupGuid = gnsClient.lookupGuid(proxyGroupName);

    // Check if we are a member of the group
    boolean isVerified = false;
    try {
        JSONArray members = gnsClient.groupGetMembers(groupGuid, myGuid);
        for (int i = 0; i < members.length(); i++) {
            if (myGuid.getGuid().equals(members.get(i))) {
                isVerified = true;
                break;
            }
        }
    } catch (Exception e) {
        /*
         * At this point we couldn't get or parse the member list probably because
         * we don't have read access to it. This means we are not a verified
         * member.
         */
        logger.log(Level.INFO,
                "Could not access the proxy group member list because we are not likely a group member yet ("
                        + e + ")");
    }

    // Make sure we advertise ourselves as a proxy and make the field readable
    // by everyone
    gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVICE_TYPE_FIELD,
            new JSONArray().put(GnsConstants.PROXY_SERVICE), myGuid);
    gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.SERVICE_TYPE_FIELD, null);
    // Publish external IP (readable by everyone)
    InetSocketAddress externalIP = (InetSocketAddress) proxySocketAddres;
    gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.PROXY_EXTERNAL_IP_FIELD,
            new JSONArray().put(externalIP.getAddress().getHostAddress() + ":" + externalIP.getPort()), myGuid);
    gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.PROXY_EXTERNAL_IP_FIELD, null);

    // Update our location if geolocation resolution worked
    if (proxyInfo.getLatLong() != null)
        gnsClient.setLocation(proxyInfo.getLatLong().getLongitude(), proxyInfo.getLatLong().getLatitude(),
                myGuid);

    if (!isVerified) {
        logger.log(Level.WARNING,
                "This proxy has not been verified yet, it will stay in the unverified list until it gets added to the proxy group");
    }

    gnsTimer = new GnsTimerKeepalive(gnsCredentials, myGuid, 1000);
    gnsTimer.start();
}

From source file:net.grinder.engine.agent.PropertyBuilder.java

/**
 * Rebase Host String.. add the missing ip addresses if only host is
 * provided../*from w w w .j a  v  a 2  s. co  m*/
 *
 * @param hostString host string
 * @return completed host string.
 */
public String rebaseHostString(String hostString) {
    String[] split = StringUtils.split(hostString, ",");
    StringBuilder newHostString = new StringBuilder();
    boolean first = true;
    for (String pair : split) {
        if (!first) {
            newHostString.append(",");
        }
        first = false;
        if (pair.startsWith(":")) {
            newHostString.append(pair);
        } else if (pair.contains(":")) {
            newHostString.append(pair);
        } else if (securityEnabled) {
            // When the security mode is enabled, we should provide all IPs
            boolean eachFirst = true;
            for (InetAddress each : NetworkUtils.getIpsFromHost(pair)) {
                if (!eachFirst) {
                    newHostString.append(",");
                }
                newHostString.append(pair).append(":").append(each.getHostAddress());
                eachFirst = false;
            }
        }
    }
    return newHostString.toString();
}

From source file:com.btobits.automator.mail.smtp.SMTPProcessor.java

/**
 * Entrypoint for the Thread, this method handles the interaction with
 * the client socket./*  w  w  w  .  j  a  va  2s . c  om*/
 */
public void run() {

    try {
        //Set the socket to timeout every 10 seconds so it does not
        //just block forever.
        serverSocket.setSoTimeout(10 * 1000);
    } catch (SocketException se) {
        log.fatal("Error initializing Socket Timeout in SMTPProcessor");
    }

    while (running) {
        try {
            socket = serverSocket.accept();

            //Set the socket to timeout after 10 seconds
            socket.setSoTimeout(10 * 1000);

            //Prepare the input and output streams.
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            InetAddress remoteAddress = socket.getInetAddress();
            clientIp = remoteAddress.getHostAddress();

            if (log.isInfoEnabled()) {
                log.info(remoteAddress.getHostName() + "(" + clientIp + ") socket connected via SMTP.");
            }

            write(WELCOME_MESSAGE);

            //Initialize the input message.
            message = new SMTPMessage();

            //Parses the input for commands and delegates to the appropriate methods.
            handleCommands();

        } catch (InterruptedIOException iioe) {
            //This is fine, it should time out every 10 seconds if
            //a connection is not made.
        }
        //If any exception gets to here uncaught, it means we should just disconnect.
        catch (Throwable e) {
            log.debug("Disconnecting Exception:", e);
            log.info("Disconnecting");
            try {
                write(MESSAGE_DISCONNECT);
            } catch (Exception e1) {
                log.debug("Error sending disconnect message.", e1);
                //Nothing to do.
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException ioe) {
                log.debug("Error disconnecting.", ioe);
                //Nothing to do.
            }
        }
    }
    log.warn("SMTPProcessor shut down gracefully");
}

From source file:com.sshtools.daemon.SshServer.java

/**
 *
 *
 * @param socket/*from   w  ww .j a  v  a  2 s.c om*/
 *
 * @return
 *
 * @throws IOException
 */
protected TransportProtocolServer createSession(Socket socket) throws IOException {
    log.debug("Initializing connection");

    InetAddress address = socket.getInetAddress();
    /*( (InetSocketAddress) socket
         .getRemoteSocketAddress()).getAddress();*/

    log.debug("Remote Hostname: " + address.getHostName());
    log.debug("Remote IP: " + address.getHostAddress());

    TransportProtocolServer transport = new TransportProtocolServer();

    // Create the Authentication Protocol
    AuthenticationProtocolServer authentication = new AuthenticationProtocolServer();

    // Create the Connection Protocol
    ConnectionProtocol connection = new ConnectionProtocol();

    // Configure the connections services
    configureServices(connection);

    // Allow the Connection Protocol to be accepted by the Authentication Protocol
    authentication.acceptService(connection);

    // Allow the Authentication Protocol to be accepted by the Transport Protocol
    transport.acceptService(authentication);

    transport.startTransportProtocol(new ConnectedSocketTransportProvider(socket),
            new SshConnectionProperties());

    return transport;
}

From source file:com.liferay.portal.search.elasticsearch.internal.connection.EmbeddedElasticsearchConnection.java

protected void configureNetworking() {
    String networkBindHost = elasticsearchConfiguration.networkBindHost();

    if (Validator.isNotNull(networkBindHost)) {
        settingsBuilder.put("network.bind.host", networkBindHost);
    }/* ww  w  . j  a  va  2  s .  c  o m*/

    String networkHost = elasticsearchConfiguration.networkHost();

    if (Validator.isNull(networkBindHost) && Validator.isNull(networkHost)
            && Validator.isNull(elasticsearchConfiguration.networkPublishHost())) {

        InetAddress localBindInetAddress = clusterSettingsContext.getLocalBindInetAddress();

        if (localBindInetAddress != null) {
            networkHost = localBindInetAddress.getHostAddress();
        }
    }

    if (Validator.isNotNull(networkHost)) {
        settingsBuilder.put("network.host", networkHost);
    }

    String networkPublishHost = elasticsearchConfiguration.networkPublishHost();

    if (Validator.isNotNull(networkPublishHost)) {
        settingsBuilder.put("network.publish.host", networkPublishHost);
    }

    String transportTcpPort = elasticsearchConfiguration.transportTcpPort();

    if (Validator.isNotNull(transportTcpPort)) {
        settingsBuilder.put("transport.tcp.port", transportTcpPort);
    }
}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

@Override
public Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException {
    Connection connection = this.getConnection(node);
    if (connection == null) {
        return false;
    }//w  ww .java 2  s . c o  m

    OVSDBConfigService ovsdbTable = (OVSDBConfigService) ServiceHelper
            .getGlobalInstance(OVSDBConfigService.class, this);
    OvsDBSet<String> protocols = new OvsDBSet<String>();

    String ofVersion = System.getProperty("ovsdb.of.version", OPENFLOW_10);
    switch (ofVersion) {
    case OPENFLOW_13:
        protocols.add("OpenFlow13");
        break;
    case OPENFLOW_10:
    default:
        protocols.add("OpenFlow10");
        break;
    }

    Bridge bridge = new Bridge();
    bridge.setProtocols(protocols);
    Status status = ovsdbTable.updateRow(node, Bridge.NAME.getName(), null, bridgeUUID, bridge);
    logger.debug("Bridge {} updated to {} with Status {}", bridgeUUID, protocols.toArray()[0], status);

    List<InetAddress> ofControllerAddrs = this.getControllerIPAddresses(connection);
    short ofControllerPort = getControllerOFPort();
    for (InetAddress ofControllerAddress : ofControllerAddrs) {
        String newController = "tcp:" + ofControllerAddress.getHostAddress() + ":" + ofControllerPort;
        Controller controllerRow = new Controller();
        controllerRow.setTarget(newController);
        if (ovsdbTable != null) {
            ovsdbTable.insertRow(node, Controller.NAME.getName(), bridgeUUID, controllerRow);
        }
    }
    return true;
}

From source file:com.mobiperf.speedometer.measurements.PingTask.java

@Override
public MeasurementResult call() throws MeasurementError {
    PingDesc desc = (PingDesc) measurementDesc;
    try {// w  w  w .  j  av a2  s  .  c o m
        /*
         * only select ipv4 address
         */
        InetAddress[] addrs = InetAddress.getAllByName(desc.target);

        for (InetAddress address : addrs) {
            // All ping methods ping against targetIp rather than desc.target
            targetIp = address.getHostAddress();
            if (PingTask.isValidIpv4(targetIp)) {
                break;
            }

        }
        if (!PingTask.isValidIpv4(targetIp)) {
            throw new MeasurementError("No Ipv4 address for host" + desc.target);
        }

    } catch (UnknownHostException e) {
        throw new MeasurementError("Unknown host " + desc.target);
    }

    try {
        Logger.i("running ping command");
        /*
         * Prevents the phone from going to low-power mode where WiFi turns off
         */
        return executePingCmdTask();
    } catch (MeasurementError e) {
        try {
            Logger.i("running java ping");
            return executeJavaPingTask();
        } catch (MeasurementError ee) {
            Logger.i("running http ping");
            return executeHttpPingTask();
        }
    }
}

From source file:net.pms.network.RequestHandlerV2.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    RequestV2 request = null;/*from  w  ww.  ja va  2 s  .co m*/
    RendererConfiguration renderer = null;
    String userAgentString = null;
    ArrayList<String> identifiers = new ArrayList<>();

    HttpRequest nettyRequest = this.nettyRequest = (HttpRequest) e.getMessage();

    InetSocketAddress remoteAddress = (InetSocketAddress) e.getChannel().getRemoteAddress();
    InetAddress ia = remoteAddress.getAddress();

    // Is the request from our own Cling service, i.e. self-originating?
    boolean isSelf = ia.getHostAddress().equals(PMS.get().getServer().getHost())
            && nettyRequest.headers().get(HttpHeaders.Names.USER_AGENT) != null
            && nettyRequest.headers().get(HttpHeaders.Names.USER_AGENT).contains("UMS/");

    // Filter if required
    if (isSelf || filterIp(ia)) {
        e.getChannel().close();
        LOGGER.trace(isSelf ? ("Ignoring self-originating request from " + ia + ":" + remoteAddress.getPort())
                : ("Access denied for address " + ia + " based on IP filter"));
        return;
    }

    LOGGER.trace("Opened request handler on socket " + remoteAddress);
    PMS.get().getRegistry().disableGoToSleep();
    request = new RequestV2(nettyRequest.getMethod().getName(), nettyRequest.getUri().substring(1));
    LOGGER.trace("Request: " + nettyRequest.getProtocolVersion().getText() + " : " + request.getMethod() + " : "
            + request.getArgument());

    if (nettyRequest.getProtocolVersion().getMinorVersion() == 0) {
        request.setHttp10(true);
    }

    HttpHeaders headers = nettyRequest.headers();

    // The handler makes a couple of attempts to recognize a renderer from its requests.
    // IP address matches from previous requests are preferred, when that fails request
    // header matches are attempted and if those fail as well we're stuck with the
    // default renderer.

    // Attempt 1: try to recognize the renderer by its socket address from previous requests
    renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);

    // If the renderer exists but isn't marked as loaded it means it's unrecognized
    // by upnp and we still need to attempt http recognition here.
    if (renderer == null || !renderer.loaded) {
        // Attempt 2: try to recognize the renderer by matching headers
        renderer = RendererConfiguration.getRendererConfigurationByHeaders(headers.entries(), ia);
    }

    if (renderer != null) {
        request.setMediaRenderer(renderer);
    }

    Set<String> headerNames = headers.names();
    Iterator<String> iterator = headerNames.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        String headerLine = name + ": " + headers.get(name);
        LOGGER.trace("Received on socket: " + headerLine);

        if (headerLine.toUpperCase().startsWith("USER-AGENT")) {
            userAgentString = headerLine.substring(headerLine.indexOf(':') + 1).trim();
        }

        try {
            StringTokenizer s = new StringTokenizer(headerLine);
            String temp = s.nextToken();
            if (temp.toUpperCase().equals("SOAPACTION:")) {
                request.setSoapaction(s.nextToken());
            } else if (temp.toUpperCase().equals("CALLBACK:")) {
                request.setSoapaction(s.nextToken());
            } else if (headerLine.toUpperCase().contains("RANGE: BYTES=")) {
                String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13)
                        .trim();
                StringTokenizer st = new StringTokenizer(nums, "-");
                if (!nums.startsWith("-")) {
                    request.setLowRange(Long.parseLong(st.nextToken()));
                }
                if (!nums.startsWith("-") && !nums.endsWith("-")) {
                    request.setHighRange(Long.parseLong(st.nextToken()));
                } else {
                    request.setHighRange(-1);
                }
            } else if (headerLine.toLowerCase().contains("transfermode.dlna.org:")) {
                request.setTransferMode(headerLine
                        .substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
            } else if (headerLine.toLowerCase().contains("getcontentfeatures.dlna.org:")) {
                request.setContentFeatures(headerLine
                        .substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28)
                        .trim());
            } else {
                Matcher matcher = TIMERANGE_PATTERN.matcher(headerLine);
                if (matcher.find()) {
                    String first = matcher.group(1);
                    if (first != null) {
                        request.setTimeRangeStartString(first);
                    }
                    String end = matcher.group(2);
                    if (end != null) {
                        request.setTimeRangeEndString(end);
                    }
                } else {
                    /** If we made it to here, none of the previous header checks matched.
                     * Unknown headers make interesting logging info when we cannot recognize
                     * the media renderer, so keep track of the truly unknown ones.
                     */
                    boolean isKnown = false;

                    // Try to match known headers.
                    String lowerCaseHeaderLine = headerLine.toLowerCase();
                    for (String knownHeaderString : KNOWN_HEADERS) {
                        if (lowerCaseHeaderLine.startsWith(knownHeaderString)) {
                            isKnown = true;
                            break;
                        }
                    }

                    // It may be unusual but already known
                    if (!isKnown && renderer != null) {
                        String additionalHeader = renderer.getUserAgentAdditionalHttpHeader();
                        if (StringUtils.isNotBlank(additionalHeader)
                                && lowerCaseHeaderLine.startsWith(additionalHeader)) {
                            isKnown = true;
                        }
                    }

                    if (!isKnown) {
                        // Truly unknown header, therefore interesting. Save for later use.
                        identifiers.add(headerLine);
                    }
                }
            }
        } catch (Exception ee) {
            LOGGER.error("Error parsing HTTP headers", ee);
        }
    }

    // Still no media renderer recognized?
    if (renderer == null) {

        // Attempt 3: Not really an attempt; all other attempts to recognize
        // the renderer have failed. The only option left is to assume the
        // default renderer.
        renderer = RendererConfiguration.resolve(ia, null);
        request.setMediaRenderer(renderer);
        if (renderer != null) {
            LOGGER.trace("Using default media renderer: " + renderer.getConfName());

            if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
                // We have found an unknown renderer
                identifiers.add(0, "User-Agent: " + userAgentString);
                renderer.setIdentifiers(identifiers);
                LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers:"
                        + StringUtils.join(identifiers, ", "));
                PMS.get().setRendererFound(renderer);
            }
        } else {
            // If RendererConfiguration.resolve() didn't return the default renderer
            // it means we know via upnp that it's not really a renderer.
            return;
        }
    } else {
        if (userAgentString != null) {
            LOGGER.trace("HTTP User-Agent: " + userAgentString);
        }

        LOGGER.trace("Recognized media renderer: " + renderer.getRendererName());
    }

    if (nettyRequest.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) {
        byte data[] = new byte[(int) HttpHeaders.getContentLength(nettyRequest)];
        ChannelBuffer content = nettyRequest.getContent();
        content.readBytes(data);
        request.setTextContent(new String(data, "UTF-8"));
    }

    LOGGER.trace(
            "HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-" + request.getHighRange());

    writeResponse(ctx, e, request, ia);
}

From source file:de.yaacc.upnp.server.contentdirectory.YaaccContentDirectory.java

/**
 * get the ip address of the device/*from w w  w.  j a v  a  2 s .  c o  m*/
 * 
 * @return the address or null if anything went wrong
 * 
 */
public String getIpAddress() {
    String hostAddress = null;
    try {
        for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                .getNetworkInterfaces(); networkInterfaces.hasMoreElements();) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            for (Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); inetAddresses
                    .hasMoreElements();) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {

                    hostAddress = inetAddress.getHostAddress();
                }

            }
        }
    } catch (SocketException se) {
        Log.d(YaaccUpnpServerService.class.getName(), "Error while retrieving network interfaces", se);
    }
    // maybe wifi is off we have to use the loopback device
    hostAddress = hostAddress == null ? "0.0.0.0" : hostAddress;
    return hostAddress;
}

From source file:net.pms.configuration.WebRender.java

@Override
public boolean associateIP(InetAddress sa) {
    ip = sa.getHostAddress();
    return super.associateIP(sa);
}