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:org.scassandra.http.client.CurrentClient.java

public ClosedConnectionReport closeConnections(CloseType closeType, InetAddress address) {
    return closeConnectionsByUrl(closeType, "/" + address.getHostAddress());
}

From source file:com.orangelabs.rcs.platform.network.AndroidNetworkFactory.java

/**
 * Returns the local IP address of a given network interface
 * /*from  w  w  w  .  j a  v  a2s.  c  o m*/
 * @param dnsEntry remote address to find an according local socket address
  * @param type the type of the network interface, should be either
  *        {@link android.net.ConnectivityManager#TYPE_WIFI} or {@link android.net.ConnectivityManager#TYPE_MOBILE}
 * @return Address
 */
// Changed by Deutsche Telekom
public String getLocalIpAddress(DnsResolvedFields dnsEntry, int type) {
    String ipAddress = null;
    try {
        // What kind of remote address (P-CSCF) are we trying to reach?
        boolean isIpv4 = InetAddressUtils.isIPv4Address(dnsEntry.ipAddress);

        // check all available interfaces
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); (en != null)
                && en.hasMoreElements();) {
            NetworkInterface netIntf = (NetworkInterface) en.nextElement();
            for (Enumeration<InetAddress> addr = netIntf.getInetAddresses(); addr.hasMoreElements();) {
                InetAddress inetAddress = addr.nextElement();
                ipAddress = IpAddressUtils.extractHostAddress(inetAddress.getHostAddress());
                // if IP address version doesn't match to remote address
                // version then skip
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && (InetAddressUtils.isIPv4Address(ipAddress) == isIpv4)) {
                    String intfName = netIntf.getDisplayName().toLowerCase();
                    // some devices do list several interfaces though only
                    // one is active
                    if (((type == ConnectivityManager.TYPE_WIFI) && intfName.startsWith("wlan"))
                            || ((type == ConnectivityManager.TYPE_MOBILE) && !intfName.startsWith("wlan"))) {
                        return ipAddress;
                    }
                }
            }
        }
    } catch (Exception e) {
        if (logger.isActivated()) {
            logger.error("getLocalIpAddress failed with ", e);
        }
    }
    return ipAddress;
}

From source file:org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug.java

public ServerConnectionDebug(NHttpServerConnection conn) {

    super();//from   w w w .jav  a2 s  . c o  m
    this.connectionCreationTime = (Long) conn.getContext().getAttribute(ServerHandler.CONNECTION_CREATION_TIME);
    this.requestStartTime = System.currentTimeMillis();

    // assume an entity body is not present. If present this would be overwritten
    this.requestCompletionTime = System.currentTimeMillis();

    RequestLine reqLine = conn.getHttpRequest().getRequestLine();
    this.requestURLPAth = reqLine.getUri();
    this.requestHTTPMethod = reqLine.getMethod();
    this.requestHTTPProtocol = reqLine.getProtocolVersion().toString();

    if (conn instanceof HttpInetConnection) {
        HttpInetConnection inetConn = (HttpInetConnection) conn;
        InetAddress remoteAddr = inetConn.getRemoteAddress();
        if (remoteAddr != null) {
            this.remoteClientIP = remoteAddr.getHostAddress();
        }
    }

    HttpRequest req = conn.getHttpRequest();
    this.headers = req.getAllHeaders();
}

From source file:com.frostwire.gui.library.DeviceDiscoveryClerk.java

private boolean retrieveFinger(final String key, final InetAddress address, int listeningPort, PingInfo pinfo) {
    try {/*from w w w. j ava  2s .  c o  m*/
        URI uri = new URI("http://" + address.getHostAddress() + ":" + listeningPort + "/finger");

        HttpFetcher fetcher = new HttpFetcher(uri);

        byte[] jsonBytes = fetcher.fetch();

        if (jsonBytes == null) {
            LOG.error("Failed to connnect to " + uri);
            return false;
        }

        String json = new String(jsonBytes);

        Finger finger = jsonEngine.toObject(json, Finger.class);

        synchronized (deviceCache) {
            if (deviceCache.containsKey(key)) {
                Device device = deviceCache.get(key);
                device.setFinger(finger);
                handleDeviceAlive(address, device);
            } else {
                Device device = new Device(key, address, listeningPort, finger, pinfo);
                device.setOnActionFailedListener(new OnActionFailedListener() {
                    public void onActionFailed(Device device, int action, Exception e) {
                        handleDeviceStale(key, address, device);
                    }
                });
                handleDeviceNew(key, address, device);
            }
        }

        return true;
    } catch (Throwable e) {
        LOG.error("Failed to connnect to " + address);
    }

    return false;
}

From source file:com.taobao.common.store.util.UniqId.java

private UniqId() {
    try {//from w  ww  .j a v a 2s  .com
        final InetAddress addr = InetAddress.getLocalHost();

        hostAddr = addr.getHostAddress();
    } catch (final IOException e) {
        log.error("[UniqID] Get HostAddr Error", e);
        hostAddr = String.valueOf(System.currentTimeMillis());
    }

    if (null == hostAddr || hostAddr.trim().length() == 0 || "127.0.0.1".equals(hostAddr)) {
        hostAddr = String.valueOf(System.currentTimeMillis());
    }

    if (log.isDebugEnabled()) {
        log.debug("[UniqID]hostAddr is:" + hostAddr);
    }

    try {
        mHasher = MessageDigest.getInstance("MD5");
    } catch (final NoSuchAlgorithmException nex) {
        mHasher = null;
        log.error("[UniqID]new MD5 Hasher error", nex);
    }
}

From source file:org.qi4j.library.shiro.AbstractServletTestSupport.java

@Before
public void before() throws Exception {
    InetAddress loopback = InetAddress.getLocalHost();
    int port = findFreePortOnIfaceWithPreference(loopback, 8989);
    httpHost = new HttpHost(loopback.getHostAddress(), port);
    jetty = new Server(port);
    configureJetty(jetty);/*from w ww .j av  a  2  s .  c o  m*/
    ServletContextHandler sch = new ServletContextHandler(jetty, "/",
            ServletContextHandler.SESSIONS | ServletContextHandler.NO_SECURITY);
    sch.addEventListener(new AbstractQi4jServletBootstrap() {

        public ApplicationAssembly assemble(ApplicationAssemblyFactory applicationFactory)
                throws AssemblyException {
            ApplicationAssembly app = applicationFactory.newApplicationAssembly();
            ModuleAssembly module = app.layer(TEST_LAYER).module(TEST_MODULE);

            AbstractServletTestSupport.this.assemble(module);

            return app;
        }

    });
    sch.addServlet(ServletUsingSecuredService.class, SECURED_SERVLET_PATH);
    configureServletContext(sch);
    jetty.start();
}

From source file:com.edmunds.etm.agent.impl.TcpHealthCheck.java

@Override
public void execute(HealthCheckListener listener) {

    // Ensure that the listener is set
    Validate.notNull(listener, "Health check listener is null");
    healthCheckListener = listener;/*w ww . ja va  2  s  .com*/

    // Initialize time values
    elapsedTime = 0;
    lastCheckTime = new Date().getTime();

    // Schedule the initial health check
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new HealthCheckTask(timer), interval, interval);

    if (logger.isInfoEnabled()) {
        InetAddress addr = getHostAddress();
        String message = String.format("Health check started for host %s on port %d", addr.getHostAddress(),
                port);
        logger.info(message);
    }
}

From source file:to.sven.androidrccar.host.communication.impl.SocketConnector.java

/**
 * Returns the first non-local IPv4 address of the device. 
 * @return IPv4 address as String or unknown, if no address is found.
 *//* ww w. j  a  va 2 s  . c o  m*/
private String getLocalIpAddress() {
    try {
        for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            for (InetAddress address : Collections.list(iface.getInetAddresses())) {
                if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(address.getHostAddress())) {
                    return address.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return dc.getContext().getString(android.R.string.unknownName);
}

From source file:com.gomoob.embedded.command.GetConfigurationCommand.java

private JSONObject createNet(IMongoContext mongoContext) throws CommandException {

    String bindIp = mongoContext.getMongodConfig().net().getBindIp();
    int port = mongoContext.getMongodConfig().net().getPort();
    boolean ipv6 = mongoContext.getMongodConfig().net().isIpv6();

    JSONObject serverAddress = new JSONObject();

    try {//from  w w  w  .  ja  v a 2s.com
        InetAddress inetAddress = mongoContext.getMongodConfig().net().getServerAddress();
        serverAddress.put("canonicalHostName", inetAddress.getCanonicalHostName());
        serverAddress.put("hostAddress", inetAddress.getHostAddress());
        serverAddress.put("hostName", inetAddress.getHostName());
    } catch (UnknownHostException uhex) {
        throw new CommandException(uhex);
    }

    JSONObject net = new JSONObject();
    net.put("bindIp", bindIp);
    net.put("port", port);
    net.put("ipv6", ipv6);
    net.put("serverAddress", serverAddress);

    return net;

}

From source file:com.motelabs.chromemote.bridge.MainActivity.java

private String getLocalIpAddress() {
    try {//from w  w w .  j  a v  a2s  .c o  m
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                    String ipAddr = inetAddress.getHostAddress();
                    return ipAddr;
                }
            }
        }
    } catch (SocketException ex) {
        //Log.d(TAG, ex.toString());
    }
    return null;
}