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.ohthehumanity.carrie.CarrieActivity.java

public String getLocalIpAddress() {
    try {//w w w . j  a v  a  2  s .com
        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()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        //Log.e(TAG, ex.toString());
    }
    return "";
}

From source file:com.poinsart.votar.VotarMain.java

public String getWifiIp() {
    Enumeration<NetworkInterface> en = null;
    try {//w  w  w. ja  v  a  2 s . com
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }
    while (en.hasMoreElements()) {
        NetworkInterface intf = en.nextElement();
        if (intf.getName().contains("wlan")) {
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                    //Log.d("VotAR Main", inetAddress.getHostAddress());
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    }
    return null;
}

From source file:com.panet.imeta.job.entries.sftp.SFTPClient.java

/**
 * Init Helper Class with connection settings
 * @param serverIP IP address of remote server
 * @throws KettleJobException /* w ww  . j av a2 s .  co m*/
 */
public SFTPClient(InetAddress serverIP, int serverPort, String userName) throws KettleJobException {

    if (serverIP == null || serverPort < 0 || userName == null || userName.equals("")) {
        throw new KettleJobException(
                "For a SFTP connection server name and username must be set and server port must be greater than zero.");
    }

    this.serverIP = serverIP;
    this.serverPort = serverPort;
    this.userName = userName;

    JSch jsch = new JSch();
    try {
        s = jsch.getSession(userName, serverIP.getHostAddress(), serverPort);
    } catch (JSchException e) {
        throw new KettleJobException(e);
    }
}

From source file:com.alliander.osgp.adapter.protocol.iec61850.infra.networking.Iec61850Client.java

/**
 * Connect to a given device. This will try to establish the
 * {@link ClientAssociation} between client and IED.
 *
 * @param deviceIdentification/*from w w  w  .  j  a va2s  . c  o  m*/
 *            The device identification.
 * @param ipAddress
 *            The IP address of the device.
 * @param reportListener
 *            The report listener instance which can be created using
 *            {@link Iec61850ClientEventListenerFactory}.
 * @param port
 *            The port number of the IED.
 *
 * @return An {@link Iec61850ClientAssociation} instance.
 *
 * @throws ConnectionFailureException
 *             In case the connection to the device could not be
 *             established.
 */
public Iec61850ClientAssociation connect(final String deviceIdentification, final InetAddress ipAddress,
        final Iec61850ClientBaseEventListener reportListener, final int port)
        throws ConnectionFailureException {
    // Alternatively you could use ClientSap(SocketFactory factory) to e.g.
    // connect using SSL.
    final ClientSap clientSap = new ClientSap();
    final Iec61850ClientAssociation clientAssociation;
    LOGGER.info("Attempting to connect to server: {} on port: {} with max retry count: {}",
            ipAddress.getHostAddress(), port, this.maxRetryCount);

    try {
        final ClientAssociation association = clientSap.associate(ipAddress, port, null, reportListener);
        clientAssociation = new Iec61850ClientAssociation(association, reportListener);
    } catch (final IOException e) {
        // An IOException will always indicate a fatal exception. It
        // indicates that the association was closed and
        // cannot be recovered. You will need to create a new association
        // using ClientSap.associate() in order to
        // reconnect.
        LOGGER.error("Error connecting to device: " + deviceIdentification, e);
        throw new ConnectionFailureException(e.getMessage(), e);
    }

    LOGGER.info("Connected to device: {}", deviceIdentification);
    return clientAssociation;
}

From source file:org.trpr.platform.batch.impl.spring.admin.SimpleJobConfigurationService.java

/**
 * Interface method implementation./*from  w  w  w. j  a v  a 2 s . co  m*/
 * Also sets the hostName
 * @see JobConfigurationService#setPort(int)
 */
@Override
public void setPort(int port) {
    String hostName = "";
    String ipAddr = "";
    try {
        hostName = InetAddress.getLocalHost().getHostName();
        ipAddr = InetAddress.getLocalHost().getHostAddress();
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        //Iterate through all network interfaces
        while (nets.hasMoreElements()) {
            NetworkInterface netint = (NetworkInterface) nets.nextElement();
            Enumeration<InetAddress> ips = netint.getInetAddresses();
            //Iterate through all IP adddress
            while (ips.hasMoreElements()) {
                InetAddress ip = ips.nextElement();
                //Take the first address which isn't a loopback and is in the local address
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    LOGGER.info("Host IP Address: " + ip.getHostAddress());
                    ipAddr = ip.getHostAddress();
                    break;
                }
            }
        }
    } catch (UnknownHostException e) {
        LOGGER.error("Error while getting hostName ", e);
    } catch (SocketException e) {
        LOGGER.error("Error while getting hostName ", e);
    }
    this.hostName = new JobHost(hostName, ipAddr, port);
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * Used to load all available download servers in a thread to prevent wait.
 *//*from  www .java  2  s. co m*/
@Override
public void run() {
    setName("DownloadUtils");
    if (!Locations.hasDLInitialized) {
        Benchmark.start("DlUtils");
        Logger.logInfo("DownloadUtils.run() starting");
        downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
        Random r = new Random();
        double choice = r.nextDouble();
        try { // Super catch-all to ensure the launcher always renders
            try {
                // Fetch the percentage json first
                String json = IOUtils.toString(new URL(Locations.masterRepo + "/FTB2/static/balance.json"));
                JsonElement element = new JsonParser().parse(json);

                if (element != null && element.isJsonObject()) {
                    JsonObject jso = element.getAsJsonObject();
                    if (jso != null && jso.get("minUsableLauncherVersion") != null) {
                        LaunchFrame.getInstance().minUsable = jso.get("minUsableLauncherVersion").getAsInt();
                    }
                    if (jso != null && jso.get("chEnabled") != null) {
                        Locations.chEnabled = jso.get("chEnabled").getAsBoolean();
                    }
                    if (jso != null && jso.get("repoSplitCurse") != null) {
                        JsonElement e = jso.get("repoSplitCurse");
                        Logger.logDebug("Balance Settings: " + e.getAsDouble() + " > " + choice);
                        if (e != null && e.getAsDouble() > choice) {
                            Logger.logInfo("Balance has selected Automatic:CurseCDN");
                        } else {
                            Logger.logInfo("Balance has selected Automatic:CreeperRepo");
                            Locations.masterRepoNoHTTP = Locations.chRepo.replaceAll("http://", "");
                            Locations.masterRepo = Locations.chRepo;
                            Locations.primaryCH = true;
                            downloadServers.remove("Automatic");
                            downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
                        }
                    }
                }
                Benchmark.logBenchAs("DlUtils", "Download Utils Bal");
                if (Locations.chEnabled) {
                    // Fetch servers from creeperhost using edges.json first
                    parseJSONtoMap(new URL(Locations.chRepo + "/edges.json"), "CH", downloadServers, false,
                            "edges.json");
                    Benchmark.logBenchAs("DlUtils", "Download Utils CH");
                }
                // Fetch servers list from curse using edges.json second
                parseJSONtoMap(new URL(Locations.curseRepo + "/edges.json"), "Curse", downloadServers, false,
                        "edges.json");
                Benchmark.logBenchAs("DlUtils", "Download Utils Curse");
                LoadingDialog.setProgress(80);
            } catch (IOException e) {
                int i = 10;

                // If fetching edges.json failed, assume new. is inaccessible
                // Try alternate mirrors from the cached server list in resources
                downloadServers.clear();

                Logger.logInfo("Primary mirror failed, Trying alternative mirrors");
                LoadingDialog.setProgress(i);
                parseJSONtoMap(this.getClass().getResource("/edges.json"), "Backup", downloadServers, true,
                        "edges.json");
            }
            LoadingDialog.setProgress(90);

            if (downloadServers.size() == 0) {
                Logger.logError(
                        "Could not find any working mirrors! If you are running a software firewall please allow the FTB Launcher permission to use the internet.");

                // Fall back to new. (old system) on critical failure
                downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
            } else if (!downloadServers.containsKey("Automatic")) {
                // Use a random server from edges.json as the Automatic server
                int index = (int) (Math.random() * downloadServers.size());
                List<String> keys = Lists.newArrayList(downloadServers.keySet());
                String defaultServer = downloadServers.get(keys.get(index));
                downloadServers.put("Automatic", defaultServer);
                Logger.logInfo("Selected " + keys.get(index) + " mirror for Automatic assignment");
            }
        } catch (Exception e) {
            Logger.logError("Error while selecting server", e);
            downloadServers.clear();
            downloadServers.put("Automatic", Locations.masterRepoNoHTTP);
        }

        LoadingDialog.setProgress(100);
        Locations.serversLoaded = true;

        // This line absolutely must be hit, or the console will not be shown
        // and the user/we will not even know why an error has occurred. 
        Logger.logInfo("DL ready");

        String selectedMirror = Settings.getSettings().getDownloadServer();
        String selectedHost = downloadServers.get(selectedMirror);
        String resolvedIP = "UNKNOWN";
        String resolvedHost = "UNKNOWN";
        String resolvedMirror = "UNKNOWN";

        try {
            InetAddress ipAddress = InetAddress.getByName(selectedHost);
            resolvedIP = ipAddress.getHostAddress();
        } catch (UnknownHostException e) {
            Logger.logError("Failed to resolve selected mirror: " + e.getMessage());
        }

        try {
            for (String key : downloadServers.keySet()) {
                if (key.equals("Automatic"))
                    continue;

                InetAddress host = InetAddress.getByName(downloadServers.get(key));

                if (resolvedIP.equalsIgnoreCase(host.getHostAddress())) {
                    resolvedMirror = key;
                    resolvedHost = downloadServers.get(key);
                    break;
                }
            }
        } catch (UnknownHostException e) {
            Logger.logError("Failed to resolve mirror: " + e.getMessage());
        }

        Logger.logInfo("Using download server " + selectedMirror + ":" + resolvedMirror + " on host "
                + resolvedHost + " (" + resolvedIP + ")");
        Benchmark.logBenchAs("DlUtils", "Download Utils Init");
    }
    Locations.hasDLInitialized = true;
}

From source file:com.groupon.odo.bmp.http.BrowserMobHostNameResolver.java

@Override
public InetAddress resolve(String hostname) throws IOException {
    // BEGIN ODO CHANGES
    // send requests to Odo
    hostname = "127.0.0.1";
    // END ODO CHANGES

    String remapping = remappings.get(hostname);
    if (remapping != null) {
        hostname = remapping;//w  w  w  .j av a  2s . c o m
    }

    try {
        return Address.getByAddress(hostname);
    } catch (UnknownHostException e) {
        // that's fine, this just means it's not an IP address and we gotta look it up, which is common
    }

    boolean isCached = this.isCached(hostname);

    Lookup lookup = new Lookup(Name.fromString(hostname), Type.A);
    lookup.setCache(cache);
    lookup.setResolver(resolver);

    Date start = new Date();
    Record[] records = lookup.run();
    Date end = new Date();

    if (records == null || records.length == 0) {
        throw new UnknownHostException(hostname);
    }

    // assembly the addr object
    ARecord a = (ARecord) records[0];
    InetAddress addr = InetAddress.getByAddress(hostname, a.getAddress().getAddress());

    if (!isCached) {
        // TODO: Associate the the host name with the connection. We do this because when using persistent
        // connections there won't be a lookup on the 2nd, 3rd, etc requests, and as such we wouldn't be able to
        // know what IP address we were requesting.
        RequestInfo.get().dns(start, end, addr.getHostAddress());
    } else {
        // if it is a cached hit, we just record zero since we don't want
        // to skew the data with method call timings (specially under load)
        RequestInfo.get().dns(end, end, addr.getHostAddress());
    }

    return addr;
}

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

@Override
public MeasurementResult call() throws MeasurementError {
    PingDesc desc = (PingDesc) measurementDesc;
    int ipByteLength;
    try {/*from  ww w. j  ava 2s  .  c  om*/
        InetAddress addr = InetAddress.getByName(desc.target);
        // Get the address length
        ipByteLength = addr.getAddress().length;
        Logger.i("IP address length is " + ipByteLength);
        // All ping methods ping against targetIp rather than desc.target
        targetIp = addr.getHostAddress();
        Logger.i("IP is " + targetIp);
    } 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(ipByteLength);
    } catch (MeasurementError e) {
        try {
            Logger.i("running java ping");
            return executeJavaPingTask();
        } catch (MeasurementError ee) {
            Logger.i("running http ping");
            return executeHttpPingTask();
        }
    }
}

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

/**
 * @param user//from   ww w.jav  a 2s  .  c  om
 * @param address
 */
private void handleGoodLogin(String user, InetAddress address) {
    // for long running servers, this should prevent blocking
    // of users that mistype their passwords once every day :)
    if (address != null) {
        _hackProtection.remove(address.getHostAddress());
    }
    if (_logLogin.isDebugEnabled())
        _logLogin.debug("login successfull for '" + user + "' "
                + (address == null ? "null" : address.getHostAddress()));
}

From source file:com.cloud.bridge.io.S3CAStorBucketAdapter.java

private String castorURL(String mountedRoot, String bucket, String fileName) {
    // TODO: Replace this method with access to ScspClient's Locator,
    // or add read method that returns the body as an unread
    // InputStream for use by loadObject() and loadObjectRange().

    myClient(mountedRoot); // make sure castorNodes and castorPort initialized
    InetSocketAddress nodeAddr = _locator.locate();
    if (nodeAddr == null) {
        throw new ConfigurationException("Unable to locate CAStor node with locator " + _locator);
    }/*ww w  . j a v  a  2s. co m*/
    InetAddress nodeInetAddr = nodeAddr.getAddress();
    if (nodeInetAddr == null) {
        _locator.foundDead(nodeAddr);
        throw new ConfigurationException(
                "Unable to resolve CAStor node name '" + nodeAddr.getHostName() + "' to IP address");
    }
    return "http://" + nodeInetAddr.getHostAddress() + ":" + nodeAddr.getPort() + "/" + bucket + "/" + fileName
            + (_domain == null ? "" : "?domain=" + _domain);
}