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:io.smartspaces.system.bootstrap.osgi.GeneralSmartSpacesSupportActivator.java

/**
 * Get the IP address for the system./*  w  ww. ja va 2 s  .c om*/
 *
 * @param systemConfiguration
 *          The system configuration
 *
 * @return host IP address
 */
private String getHostAddress(Configuration systemConfiguration) {
    try {
        String hostname = systemConfiguration
                .getPropertyString(SmartSpacesEnvironment.CONFIGURATION_NAME_HOST_NAME);
        if (hostname != null) {
            InetAddress address = InetAddress.getByName(hostname);
            return address.getHostAddress();
        }

        String hostInterface = systemConfiguration
                .getPropertyString(SmartSpacesEnvironment.CONFIGURATION_NAME_HOST_INTERFACE);
        if (hostInterface != null) {
            spaceEnvironment.getLog().formatInfo("Using network interface with name %s", hostInterface);
            NetworkInterface networkInterface = NetworkInterface.getByName(hostInterface);
            if (networkInterface != null) {
                for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                    if (inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            } else {
                spaceEnvironment.getLog().formatWarn("No network interface with name %s from configuration %s",
                        hostInterface, SmartSpacesEnvironment.CONFIGURATION_NAME_HOST_INTERFACE);

            }
        }

        // See if a single network interface. If so, we will use it.
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        if (interfaces.size() == 1) {
            for (InetAddress inetAddress : Collections.list(interfaces.get(0).getInetAddresses())) {
                if (inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }

        return null;
    } catch (Exception e) {
        spaceEnvironment.getLog().error("Could not obtain IP address", e);
        return UNKNOWN_HOST_ADDRESS;
    }
}

From source file:jp.primecloud.auto.process.DnsProcess.java

protected String resolveHost(String fqdn) {
    long timeout = 1000L * 60 * 5;
    long startTime = System.currentTimeMillis();
    while (true) {
        try {/*from www.  j  a  v a2 s  . c  o  m*/
            InetAddress address = InetAddress.getByName(fqdn);
            return address.getHostAddress();
        } catch (UnknownHostException ignore) {
        }
        if (System.currentTimeMillis() - startTime > timeout) {
            // 
            throw new AutoException("EPROCESS-000205", fqdn);
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignore) {
        }
    }
}

From source file:com.all.peer.commons.services.ForwardingService.java

public void forwardTo(AllMessage<?> message, InetAddress destination) {
    if (destination.equals(peerSettings.getPublicIp()) || isSandbox()) {
        log.info("Forwarding " + message.getType() + " message to the same ultrapeer.");
        messEngine.send(message);//from   w  w  w  . jav  a 2 s.com
    } else {
        log.info("Forwarding " + message.getType() + " message to ultrapeer[" + destination + "].");
        peerNetworkingService.send(peerSettings.getName(), message, destination.getHostAddress(),
                AllConstants.ULTRAPEER_PORT);
    }
}

From source file:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRoleMapperService.java

@GET
@Path("getRanges")
@Produces("text/plain")
public String getRanges(@QueryParam("role") List<String> roles) throws Throwable {

    if (log.isTraceEnabled()) {
        log.trace("getRanges(): Called with roles: " + roles);
    }/*from   w w  w  .  j av a 2s .co  m*/

    try {
        // The static content of IPRolemapper will be initialised by
        // verifyConfiguration if the configuration can be successfully
        // read.
        verifyConfiguration();
        final IPRoleMapper ipRoleMapper = new IPRoleMapper();
        final Set<IPRange> mappedRanges = ipRoleMapper.mapRoles(new TreeSet<String>(roles));

        // Build the result string.
        String rangesString = "";
        final Iterator<IPRange> rangesIterator = mappedRanges.iterator();
        while (rangesIterator.hasNext()) {

            final IPRange range = rangesIterator.next();
            final InetAddress beginAddress = range.getBeginAddress();
            final InetAddress endAddress = range.getEndAddress();

            final InetAddressComparator addressComparator = new InetAddressComparator();
            if (addressComparator.compare(beginAddress, endAddress) == 0) {
                // It's a single host...
                rangesString += beginAddress.getHostAddress();
            } else {
                // It's an actual range...
                rangesString += beginAddress.getHostAddress() + "-" + endAddress.getHostAddress();
            }

            // Append a comma if there are more roles left.
            if (rangesIterator.hasNext()) {
                rangesString += "\n";
            }
        } // end-while

        log.debug("getRanges(): returning ranges: " + rangesString);

        return rangesString;
    } catch (Throwable throwable) {
        log.error("getRoles(): Caught un-expected exception.", throwable);
        throw throwable;
    }
}

From source file:ws.argo.DemoWebClient.Browser.BrowserController.java

/**
 * Return the ip info of where the web host lives that supports the browser
 * app.//  w  ww . java  2  s .c o m
 * 
 * @return the ip addr info
 * @throws UnknownHostException if something goes wrong
 */
@GET
@Path("/ipAddrInfo")
public String getIPAddrInfo() throws UnknownHostException {

    Properties clientProps = getPropeSenderProps();

    StringBuffer buf = new StringBuffer();

    InetAddress localhost = null;
    NetworkInterface ni = null;
    try {
        localhost = InetAddress.getLocalHost();
        LOGGER.debug("Network Interface name not specified.  Using the NI for localhost "
                + localhost.getHostAddress());
        ni = NetworkInterface.getByInetAddress(localhost);
    } catch (UnknownHostException | SocketException e) {
        LOGGER.error("Error occured dealing with network interface name lookup ", e);

    }

    buf.append("<p>").append("<span style='color: red'> IP Address: </span>")
            .append(localhost.getHostAddress());
    buf.append("<span style='color: red'> Host name: </span>").append(localhost.getCanonicalHostName());
    if (ni == null) {
        buf.append("<span style='color: red'> Network Interface is NULL </span>");
    } else {
        buf.append("<span style='color: red'> Network Interface name: </span>").append(ni.getDisplayName());
    }
    buf.append("</p><p>");
    buf.append("Sending probes to " + respondToAddresses.size() + " addresses -  ");
    for (ProbeRespondToAddress rta : respondToAddresses) {
        buf.append("<span style='color: red'> Probe to: </span>")
                .append(rta.respondToAddress + ":" + rta.respondToPort);
    }
    buf.append("</p>");

    return buf.toString();
}

From source file:net.phoenix.thrift.server.ZookeeperRegisterHandler.java

@Override
public void preServe() {
    log.info("start registering zookeeper to " + this.connectString);

    // ? serverName, IP?
    if (this.serverName == null) {
        InetAddress addr;
        try {//  ww w .  ja  v a2 s  . c  om
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            log.error("Unable to get current host name.");
            return;
        }
        this.serverName = addr.getHostAddress().toString();
    }

    // this.server = event.getRpcServer();
    try {
        this.prepareZookeeper();
    } catch (IOException ex) {
        log.error("Error in create zookeeper server instance.", ex);
        return;
    }
    try {
        this.createServiceNode();
    } catch (KeeperException ex) {
        log.error("Error in creating zookeeper service node.", ex);
        return;
    } catch (InterruptedException ex) {
        log.error("Error in creating zookeeper service node.", ex);
        return;
    }
    try {
        this.startService();
    } catch (KeeperException ex) {
        log.error("Error in starting zookeeper service.", ex);
        return;
    } catch (InterruptedException ex) {
        log.error("Error in starting zookeeper service.", ex);
        return;
    }
    this.stopped = false;
    log.info("Registered to zookeeper successfully, server name:" + this.serverName + ",service name:"
            + this.serviceName + ".");
}

From source file:com.sun.socialsite.business.DefaultURLStrategy.java

/**
 * Get the appropriate Gadget Server URL for the specified request.
 * The returned URL will not end with a trailing slash.  If the
 * "socialsite.gadgets.server.url" property is populated and contains
 * any wildcards ("*"), they will be replaced with the specified
 * replacementValue./*  ww w  . jav  a 2 s .  co m*/
 */
public String getGadgetServerURL(HttpServletRequest request, String replacementValue) {

    StringBuilder sb = new StringBuilder();

    try {

        String propVal = Config.getProperty("socialsite.gadgets.server.url");
        if (propVal != null) {
            String actualValue = propVal.replace("*", replacementValue);
            sb.append(actualValue);
        } else {
            if (Config.getBooleanProperty("socialsite.gadgets.use-cookie-jail")) {
                // For now, we'll use an IP-based URL to provide a cookie jail
                InetAddress addr = InetAddress.getByName(request.getServerName());
                if (addr instanceof Inet6Address) {
                    sb.append(request.getScheme()).append("://[").append(addr.getHostAddress()).append("]");
                } else {
                    sb.append(request.getScheme()).append("://").append(addr.getHostAddress());
                }
            } else {
                sb.append(request.getScheme()).append("://").append(request.getServerName());
            }
            switch (request.getServerPort()) {
            case 80:
                if (!(request.getScheme().equalsIgnoreCase("http"))) {
                    sb.append(":").append(request.getServerPort());
                }
                break;
            case 443:
                if (!(request.getScheme().equalsIgnoreCase("https"))) {
                    sb.append(":").append(request.getServerPort());
                }
                break;
            default:
                sb.append(":").append(request.getServerPort());
            }
            sb.append(request.getContextPath());
            sb.append("/gadgets");
        }

    } catch (Exception e) {
        log.warn(e);
    }

    // We don't want our result to end with a slash
    while (sb.charAt(sb.length() - 1) == '/') {
        sb.deleteCharAt(sb.length() - 1);
    }

    return sb.toString();

}

From source file:org.fourthline.cling.android.alternate.AndroidUpnpServiceConfiguration.java

@Override
public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory) {
    return new DatagramIOImpl(new DatagramIOConfigurationImpl()) {

        @Override// www  .ja  v a2s .  c om
        synchronized public void init(InetAddress bindAddress, Router router,
                DatagramProcessor datagramProcessor) throws InitializationException {

            this.router = router;
            this.datagramProcessor = datagramProcessor;

            try {

                // don't bind to passed bindAddress to avoid reverse DNS lookup

                log.info("Creating bound socket (for datagram input/output) on: "
                        + bindAddress.getHostAddress());
                localAddress = new InetSocketAddress(0);

                socket = new MulticastSocket(localAddress);
                socket.setTimeToLive(configuration.getTimeToLive());
                socket.setReceiveBufferSize(262144); // Keep a backlog of incoming datagrams if we are not fast enough
            } catch (Exception ex) {
                throw new InitializationException(
                        "Could not initialize " + getClass().getSimpleName() + ": " + ex);
            }
        }

    };
}

From source file:com.summit.jbeacon.buoys.MultiCastResourceBuoy.java

private ResourcePacket generateResourcePacket(final Socket socket) throws MultiCastResourceBuoyException {
    ResourcePacket retVal = new ResourcePacket();
    InetAddress guessedAddress = guessHostAddress(socket);
    retVal.setDefaultHostName(guessedAddress.getHostName());
    retVal.setDefaultIp(guessedAddress.getHostAddress());
    for (int i = 0; i < availableResources.size(); i++) {
        Resource r = availableResources.get(i);
        retVal.getResources().add(r);/*  w ww.j av a 2 s. co m*/
    }
    return retVal;
}

From source file:com.tesora.dve.mysqlapi.repl.MyReplicationSlaveService.java

@Override
public boolean denyServiceStart(ExternalServiceContext ctxt) throws PEException {
    String serviceAddress = stripPort(
            GroupManager.getCoordinationServices().getExternalServiceRegisteredAddress(ctxt.getServiceName()));
    InetSocketAddress isa = GroupManager.getCoordinationServices().getMemberAddress();
    InetAddress ia = isa.getAddress();
    String ourAddress = null;/*  w w  w  . jav a 2 s.c  o m*/
    if (ia == null) {
        ourAddress = stripPort(isa.getHostName());
    } else {
        ourAddress = stripPort(ia.getHostAddress());
    }
    if (!StringUtils.equals(serviceAddress, ourAddress)) {
        // someone else has started replication slave so don't allow start
        if (logger.isDebugEnabled()) {
            logger.debug("Service '" + ctxt.getServiceName() + "' is already registered at '" + serviceAddress
                    + "'");
        }
        return true;
    }

    return false;
}