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:Main.java

public static String getLocalIpAddress() {
    String result = "";
    boolean exit = false;
    try {/*ww  w  .jav  a 2  s.  c om*/
        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() && !(inetAddress.toString().indexOf(":")>=0)) {
                //                       return inetAddress.getHostAddress().toString();
                //                   }
                //                  Log.v("","ip="+inetAddress.getHostAddress()+
                //                        ", name="+intf.getName());
                if (inetAddress.isSiteLocalAddress()) {
                    result = inetAddress.getHostAddress();
                    //                       Log.v("","result="+result+", name="+intf.getName()+"-");
                    if (intf.getName().equals("wlan0")) {
                        exit = true;
                        break;
                    }
                }
            }
            if (exit)
                break;
        }
    } catch (SocketException ex) {
        Log.e(DEBUG_TAG, ex.toString());
        result = "192.168.0.1";
    }
    //      Log.v("","getLocalIpAddress result="+result);
    if (result.equals(""))
        result = "192.168.0.1";
    return result;
}

From source file:fiftyfive.wicket.util.LoggingUtils.java

/**
 * Returns the IP address hosting this JVM, or {@code null} if it could
 * not be determined./*from  ww  w.  java2 s.  c o  m*/
 */
public static String getHostIpAddress() {
    try {
        InetAddress host = InetAddress.getLocalHost();
        return host.getHostAddress();
    } catch (Exception ex) {
        // ignore
    }
    return null;
}

From source file:com.google.appinventor.components.runtime.BlockyTalky.java

private static String getIPAddress(boolean useIPv4) {
    try {//from ww w. j a  va2s.  c  om
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:edu.umass.cs.gnsserver.installer.EC2Runner.java

private static String getHostIPSafe(String hostname) {
    InetAddress inetAddress;
    try {//from   www  .  j a  v  a  2s .  com
        inetAddress = InetAddress.getByName(hostname);
        return inetAddress.getHostAddress();
    } catch (UnknownHostException e) {
        return "Unknown";
    }
}

From source file:de.jaetzold.philips.hue.HueBridge.java

private static URL constructBaseUrlFor(InetAddress address) {
    try {//w  w w.  j a  v a 2 s  .co  m
        return new URL("http://" + address.getHostAddress() + "/");
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Can not construct http URL from the given address", e);
    }
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

/**
 * Get the IP address of the network interface.
 * //  ww w  .  j a va 2 s  .c  o  m
 * @return
 */
public static final String getLocalIpAddress() {
    InetAddress inetAddress = Utils.getLocalInetAddress();
    if (inetAddress != null) {
        return inetAddress.getHostAddress().toString();
    }
    return null;
}

From source file:net.sf.mpaxs.spi.server.settings.Settings.java

private static String getOwnIP() {

    InetAddress inet2 = null;
    try {/*from w ww  .j ava  2 s  .  c  om*/
        InetAddress inet1 = InetAddress.getLocalHost();
        inet2 = InetAddress.getByName(inet1.getHostName());
        return inet2.getHostAddress();
    } catch (UnknownHostException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:edu.umass.cs.gnsserver.installer.EC2Runner.java

/**
 * This is called to initialize an EC2 host for use as A GNS server in a region. It starts the host, loads all the necessary
 * software and copies the JAR files over. We also collect info about this host, like it's IP address and geographic location.
 * When every host is initialized and we have collected all the IPs, phase two is called.
 *
 * @param region - the EC2 region where we are starting this host
 * @param runSetName - so we can terminate them all together
 * @param id - the GNS ID of this server
 * @param elasticIP/* w  w  w  .j a v  a  2  s. co  m*/
 * @param timeout
 */
public static void initAndUpdateEC2Host(RegionRecord region, String runSetName, String id, String elasticIP,
        int timeout) {
    String installScript;
    AMIRecord amiRecord = AMIRecord.getAMI(amiRecordType, region);
    if (amiRecord == null) {
        System.out.println("Invalid combination of " + amiRecordType + " and Region " + region.name());
        return;
    }
    switch (dataStoreType) {
    case CASSANDRA:
        installScript = cassandraInstallScript;
        break;
    default: // MONGO
        if (amiRecordType.toString().contains("Amazon_Linux")) {
            installScript = mongoInstallScript;
        } else {
            switch (amiRecordType) {
            case MongoDB_2_4_8_with_1000_IOPS:
                installScript = mongoShortInstallScript;
                break;
            case Mongo_2014_5_6:
                installScript = null;
                break;
            case Mongo_2014_5_6_micro:
                installScript = null;
                break;
            case Mongo_2015_6_25_vpc:
                installScript = null;
                break;
            case Mongo_2016_6_16_micro:
                installScript = null;
                break;
            default:
                System.out.println("Invalid combination of " + amiRecordType + " and " + dataStoreType);
                return;
            }
        }
    }

    String idString = id.toString();
    //    StatusModel.getInstance().queueAddEntry(id); // for the gui
    //    StatusModel.getInstance().queueUpdate(id, region.name() + ": [Unknown hostname]", null, null);
    try {
        AWSCredentials credentials = new PropertiesCredentials(new File(CREDENTIALSFILE));
        //Create Amazon Client object
        AmazonEC2 ec2 = new AmazonEC2Client(credentials);
        String nodeName = "GNS Node " + idString;
        System.out.println("Starting install for " + nodeName + " in " + region.name() + " as part of run set "
                + runSetName);
        HashMap<String, String> tags = new HashMap<>();
        tags.put("runset", runSetName);
        tags.put("id", idString);
        //      StatusModel.getInstance().queueUpdate(id, "Creating instance");
        // create an instance
        Instance instance = AWSEC2.createAndInitInstance(ec2, region, amiRecord, nodeName, keyName,
                amiRecord.getSecurityGroup(), installScript, tags, elasticIP, timeout);
        if (instance != null) {
            //        StatusModel.getInstance().queueUpdate(id, "Instance created");
            //        StatusModel.getInstance().queueUpdate(id, StatusEntry.State.INITIALIZING);
            // toString our ip
            String hostname = instance.getPublicDnsName();
            InetAddress inetAddress = InetAddress.getByName(hostname);
            String ip = inetAddress.getHostAddress();
            // and take a guess at the location (lat, long) of this host
            Point2D location = GEOLocator.lookupIPLocation(ip);
            //        StatusModel.getInstance().queueUpdate(id, hostname, ip, location);
            // update our table of instance information
            hostTable.put(id, new HostInfo(id, hostname, location));

            // and we're done
            //        StatusModel.getInstance().queueUpdate(id, "Waiting for other servers");
        } else {
            System.out.println("EC2 Instance " + idString + " in " + region.name() + " did not in start.");
            //        StatusModel.getInstance().queueUpdate(id, StatusEntry.State.ERROR, "Did not start");
            hostsThatDidNotStart.put(id, id);
        }
    } catch (IOException e) {
        System.out.println("Problem creating EC2 instance " + idString + " in " + region.name() + ": " + e);
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        System.out.println("Problem creating EC2 instance " + idString + " in " + region.name() + ": " + e);
        e.printStackTrace();
    }
}

From source file:com.asquareb.kaaval.MachineKey.java

/**
 * Method to encrypt a string. Accepts the string to be encrypted and the
 * name of the file to store the key vale which can be used for decryption
 *//*from  w  w  w  .ja  v  a  2s.  c om*/
public static String encrypt(String property, String app) throws IOException, KaavalException {

    InetAddress ip = null;
    String ipAddress = null;
    ObjectOutputStream os = null;
    NetworkInterface macAddress = null;
    byte[] macId = null;
    Cipher pbeCipher = null;
    Random rand = new Random();
    rand.nextBytes(salt);
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password));
        ip = InetAddress.getLocalHost();
        ipAddress = ip.getHostAddress();
        macAddress = NetworkInterface.getByInetAddress(ip);
        macId = macAddress.getHardwareAddress();
        MachineKey mKey = new MachineKey();
        mKey.api = ipAddress;
        mKey.macad = new String(macId);
        mKey.yek = key;
        mKey.tlas = salt;
        mKey.eti = rand.nextInt(1000);
        os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(app)));
        os.writeObject(mKey);
        os.close();
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, mKey.eti));
        return base64Encode(pbeCipher.doFinal(property.getBytes()));
    } catch (IOException e) {
        throw new KaavalException(1, "Error in key file during encryption", e);
    } catch (Exception e) {
        throw new KaavalException(2, "Errors during encryption", e);
    } finally {
        if (os != null)
            os.close();
    }
}

From source file:com.whatlookingfor.common.utils.StringUtils.java

/**
 * ?IP//from w ww .  java 2 s.co m
 *
 * @param request 
 * @return ip?
 */
public static final String getHost(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
    }
    if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    if ("127.0.0.1".equals(ip)) {
        InetAddress inet = null;
        try { // ????IP
            inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        ip = inet.getHostAddress();
    }
    // ?IPIP,IP','
    if (ip != null && ip.length() > 15) {
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
    }
    return ip;
}