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.nridge.connector.fs.con_fs.restlet.RestletApplication.java

/**
 * Returns a Restlet instance used to identify inbound requests for the
 * web service endpoints./*  w  w  w .j a  v a 2  s.  c  om*/
 *
 * @return Restlet instance.
 */
@Override
public Restlet createInboundRoot() {
    Restlet restletRoot;
    Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Context restletContext = getContext();
    Router restletRouter = new Router(restletContext);

    String propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.host_names";
    String hostNames = mAppMgr.getString(propertyName);
    if (StringUtils.isEmpty(hostNames)) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();

            routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT);
            routerAttachEndPoints(restletRouter, inetAddress.getHostName());
            routerAttachEndPoints(restletRouter, inetAddress.getHostAddress());
            routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName());
        } catch (UnknownHostException e) {
            appLogger.error(e.getMessage(), e);
            routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT);
        }
    } else {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] hostNameList = mAppMgr.getStringArray(propertyName);
            for (String hostName : hostNameList)
                routerAttachEndPoints(restletRouter, hostName);
        } else
            routerAttachEndPoints(restletRouter, hostNames);
    }

    RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext);
    propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.allow_addresses";
    String allowAddresses = mAppMgr.getString(propertyName);
    if (StringUtils.isNotEmpty(allowAddresses)) {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] allowAddressList = mAppMgr.getStringArray(propertyName);
            for (String allowAddress : allowAddressList) {
                restletFilter.add(allowAddress);
                appLogger.debug("Filter Allow Address: " + allowAddress);
            }
        } else {
            restletFilter.add(allowAddresses);
            appLogger.debug("Filter Allow Address: " + allowAddresses);
        }
        restletFilter.setNext(restletRouter);
        restletRoot = restletFilter;
    } else
        restletRoot = restletRouter;

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return restletRoot;
}

From source file:edu.amc.sakai.user.PooledLDAPConnectionFactory.java

/**
 * Get the host to connect to. Attempt to resolve all addresses for a hostname when round robin DNS
 * is used.//from ww  w. j  a v  a2 s . c o  m
 *
 * We do this resolution low down in the stack as we don't want the results cached at all.
 * Unless configured otherwise the JVM will cache DNS lookups. Even if this is just for 30 seconds
 * (default in 1.6/1.7) it means when the pool is getting prebuilt at startup the connections will
 * all point to the same server.
 *
 * @return A hostname or a space separated string of IP addresses to connect to. 
 */
protected String getHost() {
    List<InetAddress> addresses = new ArrayList<InetAddress>();
    // The host may already be space separated.
    StringTokenizer hosts = new StringTokenizer(host, " ");
    while (hosts.hasMoreTokens()) {
        try {
            addresses.addAll(Arrays.asList(InetAddress.getAllByName(hosts.nextToken())));
        } catch (UnknownHostException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to resolve " + host + " not handling now, will deal with later.");
            }
        }
    }
    if (addresses.size() > 1) {
        StringBuilder resolvedHosts = new StringBuilder();
        // So that we don't always connect to the same host.
        // Is need on platforms that don't do round robin DNS well.
        Collections.shuffle(addresses);
        for (InetAddress address : addresses) {
            resolvedHosts.append(address.getHostAddress() + " ");
        }
        return resolvedHosts.toString();
    } else {
        // Just return the configured hostname and let it be resolved when making the connection.
        return host;
    }
}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Get the server addresses from interfaces.
 *///from www  .  j  ava 2s  . c  om
public static String getHostAddresses() {
    try {
        Enumeration interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        // Copy from enumeration to addresses vector, but filter loopback addresses
        ArrayList addresses = new ArrayList();
        while (interfaceEnumeration.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface) interfaceEnumeration.nextElement();
            // Remove loopback addresses
            Enumeration addressEnumeration = intf.getInetAddresses();
            while (addressEnumeration.hasMoreElements()) {
                InetAddress address = (InetAddress) addressEnumeration.nextElement();
                // Insert to addresses only if not loopback and not link local
                if ((!address.isLoopbackAddress()) && (!address.isLinkLocalAddress()))
                    addresses.add(address);
            }
        }
        // Pick one address from the remaining address space
        logger.debug("server available local addresses: " + addresses);
        // Now, multiple addresses are in the list, so copy all of them
        // into the result string.
        StringBuffer ips = new StringBuffer();
        for (int i = 0; i < addresses.size(); i++) {
            InetAddress address = (InetAddress) addresses.get(i);
            if (ips.length() > 0)
                ips.append(",");
            ips.append(address.getHostAddress());
        }
        return ips.toString();
    } catch (StoreException e) {
        throw e;
    } catch (Exception e) {
        throw new StoreException("exception while determining server address", e);
    }
}

From source file:com.digitalpebble.storm.crawler.bolt.SimpleFetcherBolt.java

private String getPolitenessKey(URL u) {
    String key = null;//from   w  ww . j a  va  2s.  c  o m
    if (QUEUE_MODE_IP.equalsIgnoreCase(queueMode)) {
        try {
            final InetAddress addr = InetAddress.getByName(u.getHost());
            key = addr.getHostAddress();
        } catch (final UnknownHostException e) {
            // unable to resolve it, so don't fall back to host name
            LOG.warn("Unable to resolve: {}, skipping.", u.getHost());
            return null;
        }
    } else if (QUEUE_MODE_DOMAIN.equalsIgnoreCase(queueMode)) {
        key = PaidLevelDomain.getPLD(u.getHost());
        if (key == null) {
            LOG.warn("Unknown domain for url: {}, using hostname as key", u.toExternalForm());
            key = u.getHost();
        }
    } else {
        key = u.getHost();
        if (key == null) {
            LOG.warn("Unknown host for url: {}, using URL string as key", u.toExternalForm());
            key = u.toExternalForm();
        }
    }
    return key.toLowerCase(Locale.ROOT);
}

From source file:com.cscao.apps.ntplib.NTPClient.java

private TimeInfo requestTime(String server, int timeout) {
    TimeInfo responseInfo = null;//from w  w w  . j  a  va2 s.  c o m
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(timeout);
    try {
        client.open();
        try {
            InetAddress hostAddr = InetAddress.getByName(server);
            //                System.out.println("> " + hostAddr.getHostName() + "/"
            //                        + hostAddr.getHostAddress());
            details += "NTP server: " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress();

            responseInfo = client.getTime(hostAddr);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (SocketException e) {
        e.printStackTrace();
    }

    client.close();
    return responseInfo;

}

From source file:com.roncoo.controller.BaseController.java

/**
 * ?IP?//  w  w  w  . j  a  v a2  s.c  o  m
 * 
 * @return
 */
public String getIpAddr(HttpServletRequest request) {
    String ipAddress = null;
    ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            // ????IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }

    }

    // ?IPIP,IP','
    if (ipAddress != null && ipAddress.length() > 15) {
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
    }
    return ipAddress;
}

From source file:nz.co.senanque.locking.sql.SQLLockFactory.java

public void afterPropertiesSet() throws Exception {

    try {/*from   w  ww. j  av a  2  s.com*/
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        m_hostAddress = getPrefix() + addr.getHostAddress();
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.mrstampy.kitchensync.message.KiSyMessage.java

/**
 * The Constructor./*from w w w .j  a  v a  2 s.  com*/
 *
 * @param address
 *          the address the InetAddress of the originator
 * @param port
 *          the port on which this message is to be sent
 * @param types
 *          the types applicable for this message
 */
public KiSyMessage(InetAddress address, int port, KiSyMessageType... types) {
    setTypes(types);
    setCreateTime(System.currentTimeMillis());

    setOriginatingHost(address.getHostAddress());
    setOriginatingPort(port);
}

From source file:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java

public void handle(ExceptionMessage muleMsg) {
    try {/*w  w w .  j a  v a 2  s .c o m*/
        Object requestMsg = muleMsg.getPayload();
        String requestString = requestMsg.toString();
        EucalyptusMessage msg = (EucalyptusMessage) BindingManager.getBinding("msgs_eucalyptus_ucsb_edu")
                .fromOM(requestString);
        Throwable ex = muleMsg.getException().getCause();
        EucalyptusMessage errMsg;

        String ipAddr = "127.0.0.1";
        List<NetworkInterface> ifaces = null;
        try {
            ifaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        } catch (SocketException e1) {
        }

        for (NetworkInterface iface : ifaces) {
            try {
                if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) {
                    for (InetAddress iaddr : Collections.list(iface.getInetAddresses())) {
                        if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) {
                            ipAddr = iaddr.getHostAddress();
                            break;
                        }
                    }
                }
            } catch (SocketException e1) {
            }
        }

        if (ex instanceof NoSuchBucketException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchBucketException) ex).getBucketName(),
                    "NoSuchBucket", "The specified bucket was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof AccessDeniedException) {
            errMsg = new WalrusBucketErrorMessageType(((AccessDeniedException) ex).getBucketName(),
                    "AccessDenied", "No U", HttpStatus.SC_FORBIDDEN, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotAuthorizedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotAuthorizedException) ex).getValue(), "Unauthorized",
                    "No U", HttpStatus.SC_UNAUTHORIZED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyOwnedByYouException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyOwnedByYouException) ex).getBucketName(),
                    "BucketAlreadyOwnedByYou",
                    "Your previous request to create the named bucket succeeded and you already own it.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyExistsException) ex).getBucketName(),
                    "BucketAlreadyExists",
                    "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketNotEmptyException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketNotEmptyException) ex).getBucketName(),
                    "BucketNotEmpty", "The bucket you tried to delete is not empty.", HttpStatus.SC_CONFLICT,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof PreconditionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((PreconditionFailedException) ex).getPrecondition(),
                    "PreconditionFailed", "At least one of the pre-conditions you specified did not hold.",
                    HttpStatus.SC_PRECONDITION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotModifiedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotModifiedException) ex).getPrecondition(),
                    "NotModified", "Object Not Modified", HttpStatus.SC_NOT_MODIFIED, msg.getCorrelationId(),
                    ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof TooManyBucketsException) {
            errMsg = new WalrusBucketErrorMessageType(((TooManyBucketsException) ex).getBucketName(),
                    "TooManyBuckets", "You have attempted to create more buckets than allowed.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof EntityTooLargeException) {
            errMsg = new WalrusBucketErrorMessageType(((EntityTooLargeException) ex).getEntityName(),
                    "EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NoSuchEntityException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchEntityException) ex).getBucketName(),
                    "NoSuchEntity", "The specified entity was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof DecryptionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((DecryptionFailedException) ex).getValue(),
                    "Decryption Failed", "Fail", SC_DECRYPTION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof ImageAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((ImageAlreadyExistsException) ex).getValue(),
                    "Image Already Exists", "Fail", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotImplementedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotImplementedException) ex).getValue(),
                    "Not Implemented", "NA", HttpStatus.SC_NOT_IMPLEMENTED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else {
            errMsg = new EucalyptusErrorMessageType(muleMsg.getComponentName(), msg, ex.getMessage());
        }
        replies.putMessage(errMsg);
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:com.bluetooth.activities.WiFiControl.java

/**
 * This method gets an IPv4 address for the user to enter in the browser.
 * /*  w  w  w  .  j  a va 2  s  . c o  m*/
 * @return The IP
 */
private String getLocalIpAddress() {
    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();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}