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.uga.cs.fluxbuster.clustering.DomainCluster.java

/**
 * Returns a string representing this DomainCluster.
 * /*from   w ww . ja  va2s . co m*/
 * @return a string representing this DomainCluster.
 */
@Override
public String toString() {
    StringBuffer buf = new StringBuffer();

    ArrayList<String> domains = new ArrayList<String>();
    HashSet<InetAddress> ipset = new HashSet<InetAddress>();
    ArrayList<InetAddress> ips = new ArrayList<InetAddress>();
    for (CandidateFluxDomain cfd : this.getCandidateDomains()) {
        domains.add(cfd.getDomainName());
        ipset.addAll(cfd.getIps());
    }
    ips.addAll(ipset);
    Collections.sort(domains);
    Collections.sort(ips, new InetAddressComparator());

    buf.append("Domains: \n");
    for (String domain : domains) {
        buf.append("\t" + domain + "\n");
    }

    buf.append("IP's: \n");
    for (InetAddress ip : ips) {
        buf.append("\t" + ip.getHostAddress() + "\n");
    }

    buf.append("Query Volume: " + this.getQueries() + "\n");
    buf.append("Distinct IPs: " + this.getIps().size() + "\n");
    buf.append("IP Diversity: " + this.getIpDiversity() + "\n");

    double sumAvgTTL = 0.0;
    for (double avgTTL : this.getAvgTTLs()) {
        sumAvgTTL += avgTTL;
    }
    buf.append("Average TTL: " + sumAvgTTL / this.getAvgTTLs().size() + "\n");

    double sumGrowthRatios = 0.0;
    for (double growthRatio : this.getGrowthRatios()) {
        sumGrowthRatios += growthRatio;
    }
    buf.append("Average Growth Ratio: " + sumGrowthRatios / this.getGrowthRatios().size() + "\n");

    buf.append("Candidate Flux Domains:\n");
    for (CandidateFluxDomain d : this.getCandidateDomains()) {
        buf.append(d.toString());
    }

    return buf.toString();
}

From source file:com.google.wireless.speed.speedometer.measurements.PingTask.java

@Override
public MeasurementResult call() throws MeasurementError {
    PingDesc desc = (PingDesc) measurementDesc;
    try {//  w ww.  j  av  a 2 s . co  m
        InetAddress addr = InetAddress.getByName(desc.target);
        // All ping methods ping against targetIp rather than desc.target
        targetIp = addr.getHostAddress();
    } catch (UnknownHostException e) {
        throw new MeasurementError("Unknown host " + desc.target);
    }

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

From source file:com.seleuco.mame4droid.NetPlay.java

public String getIPAddress() {
    try {//w  w  w. j a  va2 s  . c  o  m
        Enumeration<NetworkInterface> ifaceList;
        NetworkInterface selectedIface = null;

        // First look for a WLAN interface
        ifaceList = NetworkInterface.getNetworkInterfaces();
        while (selectedIface == null && ifaceList.hasMoreElements()) {
            NetworkInterface intf = ifaceList.nextElement();
            if (intf.getName().startsWith("wlan")) {
                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 (isIPv4)
                            return sAddr;
                    }
                }
            }
        }

        // If we didn't find that, look for an Ethernet interface
        ifaceList = NetworkInterface.getNetworkInterfaces();
        while (selectedIface == null && ifaceList.hasMoreElements()) {
            NetworkInterface intf = ifaceList.nextElement();
            if (intf.getName().startsWith("eth")) {
                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 (isIPv4)
                            return sAddr;
                    }
                }
            }
        }

        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 (isIPv4)
                        return sAddr;
                }
            }
        }
    } catch (Exception ex) {
    }
    return null;
}

From source file:com.cyberway.issue.crawler.writer.WARCWriterProcessor.java

/**
 * Return relevant values as header-like fields (here ANVLRecord, but 
 * spec-defined "application/warc-fields" type when written). Field
 * names from from DCMI Terms and the WARC/0.17 specification.
 * //from  www  .ja  v  a2  s.c  o m
 * @see com.cyberway.issue.crawler.framework.WriterPoolProcessor#getFirstrecordBody(java.io.File)
 */
@Override
protected String getFirstrecordBody(File orderFile) {
    ANVLRecord record = new ANVLRecord(7);
    record.addLabelValue("software", "Heritrix/" + Heritrix.getVersion() + " http://crawler.archive.org");
    try {
        InetAddress host = InetAddress.getLocalHost();
        record.addLabelValue("ip", host.getHostAddress());
        record.addLabelValue("hostname", host.getHostName());
    } catch (UnknownHostException e) {
        logger.log(Level.WARNING, "unable top obtain local crawl engine host", e);
    }
    record.addLabelValue("format", "WARC File Format 0.17");
    record.addLabelValue("conformsTo", "http://crawler.archive.org/warc/0.17/WARC0.17ISO.doc");
    // Get other values from order.xml 
    try {
        Document doc = XmlUtils.getDocument(orderFile);
        addIfNotBlank(record, "operator", XmlUtils.xpathOrNull(doc, "//meta/operator"));
        addIfNotBlank(record, "publisher", XmlUtils.xpathOrNull(doc, "//meta/organization"));
        addIfNotBlank(record, "audience", XmlUtils.xpathOrNull(doc, "//meta/audience"));
        addIfNotBlank(record, "isPartOf", XmlUtils.xpathOrNull(doc, "//meta/name"));
        String rawDate = XmlUtils.xpathOrNull(doc, "//meta/date");
        if (StringUtils.isNotBlank(rawDate)) {
            Date date;
            try {
                date = ArchiveUtils.parse14DigitDate(rawDate);
                addIfNotBlank(record, "created", ArchiveUtils.getLog14Date(date));
            } catch (ParseException e) {
                logger.log(Level.WARNING, "obtaining warc created date", e);
            }
        }
        addIfNotBlank(record, "description", XmlUtils.xpathOrNull(doc, "//meta/description"));
        addIfNotBlank(record, "robots",
                XmlUtils.xpathOrNull(doc, "//newObject[@name='robots-honoring-policy']/string[@name='type']"));
        addIfNotBlank(record, "http-header-user-agent",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='user-agent']"));
        addIfNotBlank(record, "http-header-from",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='from']"));
    } catch (IOException e) {
        logger.log(Level.WARNING, "obtaining warcinfo", e);
    }
    // really ugly to return as string, when it may just be merged with 
    // a couple other fields at write time, but changing would require 
    // larger refactoring
    return record.toString();
}

From source file:me.xingrz.prox.tcp.TcpProxy.java

@Override
public TcpProxySession pickSession(int sourcePort, InetAddress remoteAddress, int remotePort)
        throws IOException {
    TcpProxySession session = getSession(sourcePort);

    if (session == null || !session.getRemoteAddress().equals(remoteAddress)
            || session.getRemotePort() != remotePort) {
        session = super.pickSession(sourcePort, remoteAddress, remotePort);
        logger.v("Created session %08x local:%d -> in:%d -> out:(pending) -> %s:%d", session.hashCode(),
                sourcePort, port(), remoteAddress.getHostAddress(), remotePort);
    }//from  w  ww .  java 2s .c o m

    return session;
}

From source file:com.iflytek.spider.protocol.http.HttpBase.java

private String blockAddr(URL url, long crawlDelay) throws ProtocolException {

    String host;/*from  w  w  w  . ja  v a  2s  .  co  m*/
    if (byIP) {
        try {
            InetAddress addr = InetAddress.getByName(url.getHost());
            host = addr.getHostAddress();
        } catch (UnknownHostException e) {
            // unable to resolve it, so don't fall back to host name
            throw new HttpException(e);
        }
    } else {
        host = url.getHost();
        if (host == null)
            throw new HttpException("Unknown host for url: " + url);
        host = host.toLowerCase();
    }

    int delays = 0;
    while (true) {
        cleanExpiredServerBlocks(); // free held addresses

        Long time;
        synchronized (BLOCKED_ADDR_TO_TIME) {
            time = (Long) BLOCKED_ADDR_TO_TIME.get(host);
            if (time == null) { // address is free

                // get # of threads already accessing this addr
                Integer counter = (Integer) THREADS_PER_HOST_COUNT.get(host);
                int count = (counter == null) ? 0 : counter.intValue();

                count++; // increment & store
                THREADS_PER_HOST_COUNT.put(host, new Integer(count));

                if (count >= maxThreadsPerHost) {
                    BLOCKED_ADDR_TO_TIME.put(host, new Long(0)); // block it
                }
                return host;
            }
        }

        if (delays == maxDelays)
            throw new BlockedException("Exceeded http.max.delays: retry later.");

        long done = time.longValue();
        long now = System.currentTimeMillis();
        long sleep = 0;
        if (done == 0) { // address is still in use
            sleep = crawlDelay; // wait at least delay

        } else if (now < done) { // address is on hold
            sleep = done - now; // wait until its free
        }

        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
        }
        delays++;
    }
}

From source file:com.example.android.toyvpn.ToyVpnService.java

public String getLocalIpAddress() {
    String ipv4;//from w w  w.ja  v  a 2  s.  c o m
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                // System.out.println("ip1--:" + inetAddress);
                // System.out.println("ip2--:" + inetAddress.getHostAddress());

                // for getting IPV4 format
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {

                    String ip = inetAddress.getHostAddress().toString();
                    //  System.out.println("ip---::" + ip);
                    // return inetAddress.getHostAddress().toString();
                    return ipv4;
                }
            }
        }
    } catch (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

From source file:com.censoredsoftware.infractions.bukkit.legacy.CommandHandler.java

@Override
public boolean onCommand(CommandSender sender, Command c, String label, String[] args) {
    Player p = null;/*from w w  w. j  a v  a  2s.co m*/
    if (sender instanceof Player)
        p = (Player) sender;
    if (c.getName().equalsIgnoreCase("infractions")) {
        MiscUtil.sendMessage(p, "---------------");
        MiscUtil.sendMessage(p, "INFRACTIONS HELP");
        MiscUtil.sendMessage(p, "---------------");
        if (MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, ChatColor.GRAY + "  /cite <player> <infraction> [proof-url]");
            MiscUtil.sendMessage(p, ChatColor.GRAY + "  /uncite <player> <key>" + ChatColor.WHITE
                    + " - Find the key with " + ChatColor.YELLOW + "/history" + ChatColor.WHITE + ".");
        }
        MiscUtil.sendMessage(p, ChatColor.GRAY + "  /history [player]");
        MiscUtil.sendMessage(p,
                ChatColor.GRAY + "  /reasons " + ChatColor.WHITE + "- Shows all valid infraction reasons.");
        MiscUtil.sendMessage(p,
                ChatColor.GRAY + "  /virtues " + ChatColor.WHITE + "- Shows all valid virtue types.");
        return true;
    } else if (c.getName().equalsIgnoreCase("reasons")) {
        MiscUtil.sendMessage(p, "------------------");
        MiscUtil.sendMessage(p, "INFRACTION REASONS");
        MiscUtil.sendMessage(p, "------------------");

        for (int i = 1; i < 6; i++) {
            MiscUtil.sendMessage(p,
                    (i < 3 ? ChatColor.GREEN : i < 5 ? ChatColor.YELLOW : ChatColor.RED) + "Level " + i + ":");
            for (int j = 0; j < SettingUtil.getLevel(i).size(); j++)
                MiscUtil.sendMessage(p, "  " + SettingUtil.getLevel(i).get(j));
        }
        return true;
    } else if (c.getName().equalsIgnoreCase("cite")) {
        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, "You do not have enough permissions.");
            return true;
        }
        if (SettingUtil.getSettingBoolean("require_proof")) {
            if ((args.length != 3)) {
                MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                return false;
            }
            if (!URLUtil.isValidURL(args[2])) {
                MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                return false;
            }
        }
        if (args.length == 0 || args.length == 1) {
            MiscUtil.sendMessage(p, "Not enough arguments.");
            return false;
        }

        if (Infractions.getCompleteDossier(args[0]) == null) {
            MiscUtil.sendMessage(p, "This player hasn't joined yet.");
            return true;
        }
        // Levels
        Integer level = SettingUtil.getLevel(args[1]);
        if (level != null) {
            if (args.length == 3) {
                if (!URLUtil.isValidURL(args[2])) {
                    MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                    return false;
                }
                MiscUtil.addInfraction(MiscUtil.getInfractionsPlayer(args[0]), sender, level, args[1],
                        URLUtil.convertURL(args[2]));
            } else {
                MiscUtil.addInfraction(MiscUtil.getInfractionsPlayer(args[0]), sender, level, args[1],
                        "No proof.");
            }
            MiscUtil.sendMessage(p, ChatColor.GOLD + "Success! " + ChatColor.WHITE + "The level " + level
                    + " infraction has been received.");
            MiscUtil.kickNotify(MiscUtil.getInfractionsPlayer(args[0]), args[1]);
            return true;
        }
    } else if (c.getName().equalsIgnoreCase("uncite")) {
        if (!(args.length == 2)) {
            MiscUtil.sendMessage(p, "Not enough arguments.");
            return false;
        }
        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, "You do not have enough permissions.");
            return true;
        }

        if (MiscUtil.removeInfraction(MiscUtil.getInfractionsPlayer(args[0]), args[1])) {
            MiscUtil.sendMessage(p, "Infraction removed!");
            try {
                MiscUtil.checkScore(MiscUtil.getInfractionsPlayer(args[0]));
            } catch (NullPointerException e) {
                // player is offline
            }
            return true;
        }
        MiscUtil.sendMessage(p, "No such infraction.");
        return true;
    } else if (c.getName().equalsIgnoreCase("history")) {
        if (!(args.length == 1) && !(p == null)) {
            if (MiscUtil.ignore(p)) {
                sender.sendMessage(ChatColor.YELLOW + "Infractions does not track your history.");
                return true;
            }

            p.performCommand("history " + p.getName());
            return true;
        }
        if ((p == null) && !(args.length == 1)) {
            log.info("You must provide a username in the console.");
            return false;
        }

        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod") && !p.getName().toLowerCase().equals(args[0])) {
            p.sendMessage(ChatColor.RED + "You don't have permission to do that.");
            return true;
        }

        /**
         * DISPLAY ALL CURRENT INFRACTIONS
         */

        String player = MiscUtil.getInfractionsPlayer(args[0]);
        if (player != null) {
            sender.sendMessage("   ");

            CompleteDossier dossier = Infractions.getCompleteDossier(player);

            Integer maxScore = MiscUtil.getMaxScore(Infractions.getCompleteDossier(player).getId());
            String chatLevel = InfractionsPlugin.getLevelForChat(player);
            MiscUtil.sendMessage(p,
                    ChatColor.WHITE + (chatLevel.equals("") ? "" : chatLevel + " ") + ChatColor.YELLOW + player
                            + ChatColor.WHITE + " - " + MiscUtil.getScore(player)
                            + (maxScore == null ? " points towards a ban."
                                    : " points out of " + maxScore + " until a ban."));

            try {
                boolean staff = MiscUtil.hasPermissionOrOP(p, "infractions.mod");
                Set<Infraction> infractions = dossier.getInfractions();
                if (!infractions.isEmpty()) {
                    for (Infraction infraction : infractions) {
                        MiscUtil.sendMessage(p,
                                ChatColor.DARK_RED + " " + ChatColor.DARK_PURPLE
                                        + StringUtils.capitalize(infraction.getReason()) + ChatColor.DARK_GRAY
                                        + " - " + ChatColor.BLUE + FORMAT.format(infraction.getDateCreated()));
                        MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "     Penalty: " + ChatColor.GRAY
                                + infraction.getScore());
                        MiscUtil.sendMessage(p,
                                ChatColor.DARK_GRAY + "     Proof: " + ChatColor.GRAY
                                        + Iterables.getFirst(Collections2.transform(infraction.getEvidence(),
                                                new Function<Evidence, Object>() {
                                                    @Override
                                                    public String apply(Evidence evidence) {
                                                        return evidence.getRawData();
                                                    }
                                                }), "No Proof."));
                        if (staff) {
                            String id = MiscUtil.getInfractionId(infraction);
                            MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "     Key: " + ChatColor.GRAY + id);
                            String issuerId = infraction.getIssuer().getId();
                            if (IssuerType.STAFF.equals(infraction.getIssuer().getType())) {
                                UUID issuerUUID = UUID.fromString(issuerId);
                                ConcurrentMap<UUID, LegacyDossier> map = DataManager.getManager()
                                        .getMapFor(LegacyDossier.class);
                                if (map.containsKey(issuerUUID)
                                        && map.get(issuerUUID) instanceof CompleteDossier) {
                                    CompleteDossier issuerDossier = (LegacyCompleteDossier) map.get(issuerUUID);
                                    issuerId = issuerDossier.getLastKnownName();
                                } else {
                                    issuerId = "INVALID UUID: " + issuerId;
                                }
                            }
                            MiscUtil.sendMessage(p,
                                    ChatColor.DARK_GRAY + "     Issuer: " + ChatColor.GRAY + issuerId);
                        }
                    }
                } else
                    MiscUtil.sendMessage(p, ChatColor.DARK_GREEN + " " + ChatColor.WHITE
                            + "No infractions found for this player.");
                if (!staff)
                    return true;
                Set<InetAddress> addresses = dossier.getAssociatedIPAddresses();
                MiscUtil.sendMessage(p,
                        ChatColor.BLUE + " " + ChatColor.DARK_AQUA + "Associated IP Addresses:");
                if (addresses.isEmpty())
                    MiscUtil.sendMessage(p, ChatColor.GRAY + "     No currently known addresses.");
                else
                    for (InetAddress address : addresses) {
                        MiscUtil.sendMessage(p, ChatColor.GRAY + "     " + address.getHostAddress());
                        Collection<String> others = AsyncIPMatcherTask.getRelatives(dossier.getId());
                        if (others.size() > 1) {
                            MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "       - also associated with:");
                            for (String other : others) {
                                if (other.equals(player))
                                    continue;
                                MiscUtil.sendMessage(p,
                                        ChatColor.GRAY + "         " + ChatColor.YELLOW + other);
                            }
                        }
                    }

                sender.sendMessage("   ");
                return true;
            } catch (NullPointerException e) {
                return true;
            }
        } else {
            MiscUtil.sendMessage(p, "A player with the name \"" + args[0] + "\" cannot be found.");
            return true;
        }
    } else if (c.getName().equalsIgnoreCase("clearhistory") && p != null
            && p.hasPermission("infractions.clearhistory") && args.length > 0) {
        try {
            Player remove = Bukkit.getServer().matchPlayer(args[0]).get(0);
            Infractions.removeDossier(remove.getUniqueId());
            remove.kickPlayer(ChatColor.GREEN + "Your Infractions history has been reset--please join again.");
            return true;
        } catch (Exception error) {
            sender.sendMessage(ChatColor.RED + "Could not find that player...");
            return false;
        }
    }
    MiscUtil.sendMessage(p, "Something went wrong, please try again.");
    return false;
}

From source file:org.psit.transwatcher.TransWatcher.java

private String getBroadcastIP() {
    String myIP = null;//  w  ww .  j a v  a2s .  co  m

    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && myIP == null) {
            NetworkInterface current = interfaces.nextElement();
            notifyMessage(current.toString());
            notifyMessage("Name: " + current.getName());
            if (!current.isUp() || current.isLoopback() || current.isVirtual()
                    || !current.getName().startsWith("wl"))
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr.isLoopbackAddress())
                    continue;
                if (current_addr instanceof Inet4Address) {
                    myIP = current_addr.getHostAddress();
                    break;
                }
            }
        }
    } catch (Exception exc) {
        notifyMessage("Error determining network interfaces:\n");
    }

    if (myIP != null) {
        // broadcast for IPv4
        StringTokenizer st = new StringTokenizer(myIP, ".");
        StringBuffer broadcastIP = new StringBuffer();
        // hate that archaic string puzzle
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append("255");
        return broadcastIP.toString();
    }

    return null;
}