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:com.cloud.storage.template.HttpTemplateDownloader.java

private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
    try {/*w w  w. j a va2  s  .c  om*/
        URI uri = new URI(url);
        if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) {
            throw new IllegalArgumentException("Unsupported scheme for url");
        }
        int port = uri.getPort();
        if (!(port == 80 || port == 443 || port == -1)) {
            throw new IllegalArgumentException("Only ports 80 and 443 are allowed");
        }

        if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
            port = 443;
        } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
            port = 80;
        }

        String host = uri.getHost();
        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress()
                    || hostAddr.isMulticastAddress()) {
                throw new IllegalArgumentException("Illegal host specified in url");
            }
            if (hostAddr instanceof Inet6Address) {
                throw new IllegalArgumentException(
                        "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
            }
            return new Pair<String, Integer>(host, port);
        } catch (UnknownHostException uhe) {
            throw new IllegalArgumentException("Unable to resolve " + host);
        }
    } catch (IllegalArgumentException iae) {
        s_logger.warn("Failed uri validation check: " + iae.getMessage());
        throw iae;
    } catch (URISyntaxException use) {
        s_logger.warn("Failed uri syntax check: " + use.getMessage());
        throw new IllegalArgumentException(use.getMessage());
    }
}

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

/**
 * user name is not case sensitive any more
 * @param user/*from w w w. ja  v a 2s  . c om*/
 * @param password
 * @param address
 * @return true if all operations succeed
 * @throws NoSuchAlgorithmException if SHA is not supported
 * @throws UnsupportedEncodingException if UTF-8 is not supported
 * @throws AccountModificationException  if we were unable to modify the account
 * @throws AccountBannedException  if account is banned
 * @throws AccountWrongPasswordException if the password is wrong
 */
public boolean loginValid(String user, String password, InetAddress address)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, AccountModificationException,
        AccountBannedException, AccountWrongPasswordException {
    _logLoginTries.info(
            "User trying to connect  '" + user + "' " + (address == null ? "null" : address.getHostAddress()));

    // o Convert password in utf8 byte array
    // ----------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] raw = password.getBytes("UTF-8");
    byte[] hash = md.digest(raw);

    // o find Account
    // -------------
    Accounts acc = _service.getAccountById(user);

    // If account is not found
    // try to create it if AUTO_CREATE_ACCOUNTS is activated
    // or return false
    // ------------------------------------------------------
    if (acc == null) {
        if (handleAccountNotFound(user, address, hash))
            return true;
        else
            throw new AccountWrongPasswordException(user);
    }
    // If account is found
    // check ban state
    // check password and update last ip/last active
    // ---------------------------------------------
    else {
        // check the account is not ban
        if (acc.getAccessLevel() < 0) {
            throw new AccountBannedException(user);
        }
        try {
            checkPassword(hash, acc);
            acc.setLastactive(new BigDecimal(System.currentTimeMillis()));
            if (address != null) {
                acc.setLastIp(address.getHostAddress());
            }
            _service.addOrUpdateAccount(acc);
            handleGoodLogin(user, address);
        }
        // If password are different
        // -------------------------
        catch (AccountWrongPasswordException e) {
            handleBadLogin(user, password, address);
            throw e;
        }
    }

    return true;
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
public void init(ServletConfig config) {
    /// List possible local address
    try {/*from  w w w .  j a va2s. c  o  m*/
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual())
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr instanceof Inet4Address)
                    ourIPs.add(current_addr.getHostAddress());
            }
        }
    } catch (Exception e) {
    }

    servContext = config.getServletContext();
    backend = config.getServletContext().getInitParameter("backendserver");
    server = config.getServletContext().getInitParameter("fileserver");
    try {
        String dataProviderName = config.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.jcraft.weirdx.XDMCP.java

void getLocalHost(String name) {
    myaddress = new byte[4];
    try {/*w w  w  . j  a  v a  2  s  .  c o  m*/
        InetAddress local;
        if (name != null && name.length() > 0) {
            local = InetAddress.getByName(name);
        } else {
            local = InetAddress.getLocalHost();
        }
        byte[] b = local.getHostAddress().getBytes();
        int bi = 0;
        for (int i = 0; i < 4; i++) {
            myaddress[i] = 0;
            while (bi < b.length && b[bi] != '.') {
                myaddress[i] = (byte) (myaddress[i] * 10 + (b[bi] - '0'));
                bi++;
            }
            if (b.length <= bi)
                break;
            bi++;
        }
    } catch (Exception e) {
        LOG.error(e);
    }
}

From source file:dk.netarkivet.harvester.harvesting.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.
 *
 * @see org.archive.crawler.framework.WriterPoolProcessor#getFirstrecordBody(java.io.File)
 *///from   www.j  a v  a 2  s  . c om
@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.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.log(Level.WARNING, "unable top obtain local crawl engine host", e);
    }

    // conforms to ISO 28500:2009 as of May 2009
    // as described at http://bibnum.bnf.fr/WARC/
    // latest draft as of November 2008
    record.addLabelValue("format", "WARC File Format 1.0");
    record.addLabelValue("conformsTo", "http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf");

    // 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"));

        // disabling "created" field per HER-1634
        // though it's theoretically useful as a means of distinguishing
        // one crawl from another, the current usage/specification is too
        // vague... in particular a 'created' field in the 'warcinfo' is
        // reasonable to interpret as applying to the WARC-unit, rather
        // than the crawl-job-unit so we remove it and see if anyone
        // complains or makes a case for restoring it in a less-ambiguous
        // manner
        // 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']"));
        if (metadataMap == null) {
            //metadataMap = getMetadataItems();
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(H1HeritrixTemplate.METADATA_ITEMS_XPATH);
            Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
            //NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            //Node node = nodeList.item(0);
            if (node != null) {
                NodeList nodeList = node.getChildNodes();
                if (nodeList != null) {
                    metadataMap = new HashMap();
                    for (int i = 0; i < nodeList.getLength(); ++i) {
                        node = nodeList.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            String typeName = node.getNodeName();
                            if ("string".equals(typeName)) {
                                Node attribute = node.getAttributes().getNamedItem("name");
                                if (attribute != null && attribute.getNodeType() == Node.ATTRIBUTE_NODE) {
                                    String key = attribute.getNodeValue();
                                    if (key != null && key.length() > 0) {
                                        String value = node.getTextContent();
                                        metadataMap.put(key, value);
                                        // debug
                                        //System.out.println(key + "=" + value);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, "Error obtaining warcinfo", e);
    } catch (XPathExpressionException e) {
        logger.log(Level.WARNING, "Error obtaining metadata items", e);
    }

    // add fields from harvesInfo.xml version 0.4
    /*
     * <harvestInfo> <version>0.4</version> <jobId>1</jobId> <priority>HIGHPRIORITY</priority>
     * <harvestNum>0</harvestNum> <origHarvestDefinitionID>1</origHarvestDefinitionID>
     * <maxBytesPerDomain>500000000</maxBytesPerDomain> <maxObjectsPerDomain>2000</maxObjectsPerDomain>
     * <orderXMLName>default_orderxml</orderXMLName>
     * <origHarvestDefinitionName>netarkivet</origHarvestDefinitionName> <scheduleName>Once_a_week</scheduleName>
     * <harvestFilenamePrefix>1-1</harvestFilenamePrefix> <jobSubmitDate>Some date</jobSubmitDate>
     * <performer>undefined</performer> </harvestInfo>
     */
    String netarchiveSuiteComment = "#added by NetarchiveSuite "
            + dk.netarkivet.common.Constants.getVersionString();
    ANVLRecord recordNAS = new ANVLRecord(7);

    if (metadataMap != null) {
        // Add the data from the metadataMap to the WarcInfoRecord.
        recordNAS.addLabelValue(HARVESTINFO_VERSION, (String) metadataMap.get(HARVESTINFO_VERSION));
        recordNAS.addLabelValue(HARVESTINFO_JOBID, (String) metadataMap.get(HARVESTINFO_JOBID));
        recordNAS.addLabelValue(HARVESTINFO_CHANNEL, (String) metadataMap.get(HARVESTINFO_CHANNEL));
        recordNAS.addLabelValue(HARVESTINFO_HARVESTNUM, (String) metadataMap.get(HARVESTINFO_HARVESTNUM));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONID,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONID));
        recordNAS.addLabelValue(HARVESTINFO_MAXBYTESPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXBYTESPERDOMAIN));

        recordNAS.addLabelValue(HARVESTINFO_MAXOBJECTSPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXOBJECTSPERDOMAIN));
        recordNAS.addLabelValue(HARVESTINFO_ORDERXMLNAME, (String) metadataMap.get(HARVESTINFO_ORDERXMLNAME));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONNAME,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONNAME));

        if (metadataMap.containsKey((HARVESTINFO_SCHEDULENAME))) {
            recordNAS.addLabelValue(HARVESTINFO_SCHEDULENAME,
                    (String) metadataMap.get(HARVESTINFO_SCHEDULENAME));
        }
        recordNAS.addLabelValue(HARVESTINFO_HARVESTFILENAMEPREFIX,
                (String) metadataMap.get(HARVESTINFO_HARVESTFILENAMEPREFIX));

        recordNAS.addLabelValue(HARVESTINFO_JOBSUBMITDATE, (String) metadataMap.get(HARVESTINFO_JOBSUBMITDATE));

        if (metadataMap.containsKey(HARVESTINFO_PERFORMER)) {
            recordNAS.addLabelValue(HARVESTINFO_PERFORMER, (String) metadataMap.get(HARVESTINFO_PERFORMER));
        }

        if (metadataMap.containsKey(HARVESTINFO_AUDIENCE)) {
            recordNAS.addLabelValue(HARVESTINFO_AUDIENCE, (String) metadataMap.get(HARVESTINFO_AUDIENCE));
        }
    } else {
        logger.log(Level.SEVERE, "Error missing metadata");
    }

    // 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() + netarchiveSuiteComment + "\n" + recordNAS.toString();
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java

private String getHostAddress() {
    String address = "127.0.0.1";
    try {/*from  w w w. java 2s .  com*/
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface ni = en.nextElement();
            Enumeration<InetAddress> ads = ni.getInetAddresses();
            while (ads.hasMoreElements()) {
                InetAddress ip = ads.nextElement();
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    return ip.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        log.error("", e);
    }
    return address;
}

From source file:com.jagornet.dhcp.db.JdbcIaManager.java

public IdentityAssoc findIA(InetAddress inetAddr) {
    IdentityAssoc ia = null;//from   w  w w . j  ava 2  s .c  o m
    if (inetAddr != null) {
        try {
            IaAddress iaAddr = iaAddrDao.getByInetAddress(inetAddr);
            if (iaAddr != null) {
                ia = iaDao.getById(iaAddr.getIdentityAssocId());
            }
        } catch (EmptyResultDataAccessException ex) {
            log.debug("No IaAddress found for IP=" + inetAddr.getHostAddress() + ": " + ex);
        }
    }
    return ia;
}

From source file:com.clustercontrol.repository.factory.FacilitySelector.java

/**
 * IP???ID??/*w  w w  .ja va2s  .co m*/
 * @param ipaddr IP(Inet4Address or Inet6Address)
 * @return ID?
 * @throws HinemosUnknown
 */
public static List<String> getFacilityIdByIpAddress(InetAddress ipaddr) throws HinemosUnknown {

    List<String> ret = new ArrayList<String>();

    if (ipaddr == null) {
        return ret;
    }

    try {
        String ipaddrStr = ipaddr.getHostAddress();
        if (m_log.isDebugEnabled()) {
            m_log.debug("finding node by ipaddress. (ipaddr = " + ipaddr + ")");
        }

        List<NodeInfo> facilities = null;
        if (ipaddr instanceof Inet4Address) {
            facilities = QueryUtil.getNodeByIpv4(ipaddrStr);
        }

        if (ipaddr instanceof Inet6Address) {
            facilities = QueryUtil.getNodeByIpv6(ipaddrStr);
        }

        if (facilities != null) {
            for (FacilityInfo facility : facilities) {
                ret.add(facility.getFacilityId());
            }
        }
    } catch (Exception e) {
        m_log.warn("unexpected internal error. (ipaddr = " + ipaddr + ") : " + e.getClass().getSimpleName()
                + ", " + e.getMessage(), e);
        throw new HinemosUnknown("unexpected internal error. (ipaddr = " + ipaddr + ")", e);
    }

    return ret;
}

From source file:com.github.hrpc.rpc.Server.java

/** Returns remote address as a string when invoked inside an RPC.
 *  Returns null in case of an error./* www .  j a v a  2  s  .  c o  m*/
 */
public static String getRemoteAddress() {
    InetAddress addr = getRemoteIp();
    return (addr == null) ? null : addr.getHostAddress();
}

From source file:com.zimbra.cs.pop3.Pop3Handler.java

boolean startConnection(InetAddress remoteAddr) throws IOException {
    // Set the logging context for anything logged before the first command.
    ZimbraLog.clearContext();//from w  w w .j a v a2s  .  com
    clientAddress = remoteAddr.getHostAddress();
    ZimbraLog.addIpToContext(clientAddress);

    ZimbraLog.pop.info("connected");
    if (!config.isServiceEnabled()) {
        return false;
    }
    sendOK(config.getGreeting());
    state = STATE_AUTHORIZATION;
    dropConnection = false;
    return true;
}