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.alliander.osgp.adapter.protocol.iec61850.application.services.DeviceRegistrationService.java

/**
 * After the device has registered with the platform successfully, the
 * device has to be informed that the registration worked. Disable an
 * attribute so the device will stop attempting to register once a minute.
 *
 * @param deviceIdentification//from   w ww.ja  va  2s .co  m
 *            The device identification.
 * @param ipAddress
 *            The IP address of the device.
 * @param ied
 *            The type of IED.
 *
 * @throws ProtocolAdapterException
 *             In case the connection to the device can not be established.
 */
public void disableRegistration(final String deviceIdentification, final InetAddress ipAddress, final IED ied)
        throws ProtocolAdapterException {
    this.iec61850DeviceConnectionService.connect(ipAddress.getHostAddress(), deviceIdentification, ied,
            LogicalDevice.LIGHTING);
    final Iec61850ClientAssociation iec61850ClientAssociation = this.iec61850DeviceConnectionService
            .getIec61850ClientAssociation(deviceIdentification);
    final ServerModel serverModel = this.iec61850DeviceConnectionService.getServerModel(deviceIdentification);
    final DeviceConnection deviceConnection = new DeviceConnection(
            new Iec61850Connection(iec61850ClientAssociation, serverModel), deviceIdentification, ied);

    final Function<Void> function = new Function<Void>() {

        @Override
        public Void apply() throws Exception {
            DeviceRegistrationService.this.setLocationInformation(deviceConnection);
            DeviceRegistrationService.this.disableRegistration(deviceConnection);
            if (DeviceRegistrationService.this.isReportingAfterDeviceRegistrationEnabled) {
                LOGGER.info("Reporting enabled for device: {}", deviceConnection.getDeviceIdentification());
                new Iec61850EnableReportingCommand().enableReportingOnDeviceWithoutUsingSequenceNumber(
                        DeviceRegistrationService.this.iec61850DeviceConnectionService.getIec61850Client(),
                        deviceConnection);
                // Don't disconnect now! The device should be able to send
                // reports.
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            new Iec61850ClearReportCommand().clearReportOnDevice(deviceConnection);
                        } catch (final ProtocolAdapterException e) {
                            LOGGER.error("Unable to clear report for device: "
                                    + deviceConnection.getDeviceIdentification(), e);
                        }
                        DeviceRegistrationService.this.iec61850DeviceConnectionService
                                .disconnect(deviceConnection.getDeviceIdentification());
                    }
                }, DeviceRegistrationService.this.delayAfterDeviceRegistration);
            } else {
                LOGGER.info("Reporting disabled for device: {}", deviceIdentification);
                DeviceRegistrationService.this.iec61850DeviceConnectionService
                        .disconnect(deviceConnection.getDeviceIdentification());
            }
            return null;
        }
    };

    this.iec61850DeviceConnectionService.sendCommandWithRetry(function);
}

From source file:de.yaio.commons.net.NetFirewall.java

/** 
 * checks if url is allowed/*from   w  w  w  . j a v a 2 s .  c  o  m*/
 * @param url                    url to check (check protocoll, hostname and ip)
 * @return                       true/false if it is allowed
 * @throws MalformedURLException parsing the url
 * @throws UnknownHostException  parsing the url
 */
public boolean isAllowed(final URL url) throws UnknownHostException, MalformedURLException {
    // check protocol
    if (!isInProtocolList(url.getProtocol())) {
        return false;
    }

    // check inetAddr
    InetAddress inetAddr = NetUtils.parseAddress(url.getHost());
    String hostName = inetAddr.getHostName();
    String ip = inetAddr.getHostAddress();
    if (isInHostBlackList(hostName) || isInIPBlackList(ip)) {
        // blacklisted: but check for override by whitelist
        if (isInHostWhiteList(hostName) || isInIPWhiteList(ip)) {
            return true;
        }

        // blacklisted
        return false;
    }

    return true;
}

From source file:org.doxu.g2.gwc.crawler.CrawlThread.java

private void crawlGWC(String gwcUrl, final CloseableHttpClient httpclient) {
    URI uri = basicGet(gwcUrl);/* w  ww. ja v  a  2s.  c  om*/
    InetAddress address = getIPAddress(uri);
    String ip = null;
    if (address != null) {
        ip = address.getHostAddress();
    }

    Service service = session.addService(gwcUrl);
    service.setIp(ip);
    if (ip == null) {
        service.setStatus(Status.BAD_DNS);
    } else if (isAddressBlocked(address)) {
        service.setStatus(Status.BAD_IP);
    } else if (uri != null) {
        HttpGet httpget = new HttpGet(uri);
        try (CloseableHttpResponse response = httpclient.execute(httpget)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                parseResponse(service, response);
                service.setStatus(Status.WORKING);
            } else {
                service.setStatus(Status.HTTP_ERROR);
            }
        } catch (IOException ex) {
            service.setStatus(Status.CONNECT_ERROR);
            LOGGER.log(Level.FINE, null, ex);
        }
    }
    System.out.println("Service: " + service.getUrl());
    System.out.println("  Status: " + service.getStatus());
    System.out.println("  IP: " + service.getIp());
    System.out.println("  Hosts: " + service.getHosts().size());
    System.out.println("  URLs: " + service.getUrls().size());
    System.out.println();
}

From source file:org.mule.module.http.functional.listener.HttpListenerConfigFunctionalTestCase.java

private String getNonLocalhostIp() {
    try {/*from  w  ww . j  av a 2  s. com*/
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface networkInterface : Collections.list(nets)) {
            final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && IPADDRESS_PATTERN.matcher(inetAddress.getHostAddress()).find()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
        throw new RuntimeException("Could not find network interface different from localhost");
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.servicecomb.serviceregistry.TestRegistry.java

@Test
public void testGetRealListenAddress() throws Exception {
    new Expectations(NetUtils.class) {
        {/*from  www . j  a  va2  s  . c o  m*/
            NetUtils.getHostAddress();
            result = "1.1.1.1";
        }
    };

    Assert.assertEquals("rest://172.0.0.0:8080", RegistryUtils.getPublishAddress("rest", "172.0.0.0:8080"));
    Assert.assertEquals(null, RegistryUtils.getPublishAddress("rest", null));

    URI uri = new URI(RegistryUtils.getPublishAddress("rest", "0.0.0.0:8080"));
    Assert.assertEquals("1.1.1.1:8080", uri.getAuthority());

    new Expectations(DynamicPropertyFactory.getInstance()) {
        {
            DynamicPropertyFactory.getInstance().getStringProperty(PUBLISH_ADDRESS, "");
            result = new DynamicStringProperty(PUBLISH_ADDRESS, "") {
                public String get() {
                    return "1.1.1.1";
                }
            };
        }
    };
    Assert.assertEquals("rest://1.1.1.1:8080", RegistryUtils.getPublishAddress("rest", "172.0.0.0:8080"));

    InetAddress ethAddress = Mockito.mock(InetAddress.class);
    Mockito.when(ethAddress.getHostAddress()).thenReturn("1.1.1.1");
    new Expectations(DynamicPropertyFactory.getInstance()) {
        {
            NetUtils.ensureGetInterfaceAddress("eth20");
            result = ethAddress;
            DynamicPropertyFactory.getInstance().getStringProperty(PUBLISH_ADDRESS, "");
            result = new DynamicStringProperty(PUBLISH_ADDRESS, "") {
                public String get() {
                    return "{eth20}";
                }
            };
        }
    };
    String query = URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair("country", " ")),
            StandardCharsets.UTF_8.name());
    Assert.assertEquals("rest://1.1.1.1:8080?" + query,
            RegistryUtils.getPublishAddress("rest", "172.0.0.0:8080?" + query));
}

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

@Override
public void execute(Tuple tuple) {
    String url = tuple.getStringByField("url");
    Metadata metadata = null;/* w  w  w.j a  v  a 2 s  .  co  m*/

    if (tuple.contains("metadata"))
        metadata = (Metadata) tuple.getValueByField("metadata");

    // maybe there is a field metadata but it can be null
    // or there was no field at all
    if (metadata == null)
        metadata = Metadata.empty;

    String partitionKey = null;
    String host = "";

    // IP in metadata?
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP)) {
        String ip_provided = metadata.getFirstValue("ip");
        if (StringUtils.isNotBlank(ip_provided)) {
            partitionKey = ip_provided;
            eventCounter.scope("provided").incrBy(1);
        }
    }

    if (partitionKey == null) {
        URL u;
        try {
            u = new URL(url);
            host = u.getHost();
        } catch (MalformedURLException e1) {
            eventCounter.scope("Invalid URL").incrBy(1);
            LOG.warn("Invalid URL: {}", url);
            // ack it so that it doesn't get replayed
            _collector.ack(tuple);
            return;
        }
    }

    // partition by hostname
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_HOST))
        partitionKey = host;

    // partition by domain : needs fixing
    else if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_DOMAIN)) {
        partitionKey = PaidLevelDomain.getPLD(host);
    }

    // partition by IP
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP) && partitionKey == null) {
        // try to get it from cache first
        partitionKey = cache.get(host);
        if (partitionKey != null) {
            eventCounter.scope("from cache").incrBy(1);
        } else {
            try {
                long start = System.currentTimeMillis();
                final InetAddress addr = InetAddress.getByName(host);
                partitionKey = addr.getHostAddress();
                long end = System.currentTimeMillis();
                LOG.debug("Resolved IP {} in {} msec for : {}", partitionKey, (end - start), url);

                // add to cache
                cache.put(host, partitionKey);

            } catch (final Exception e) {
                eventCounter.scope("Unable to resolve IP").incrBy(1);
                LOG.warn("Unable to resolve IP for: {}", host);
                _collector.ack(tuple);
                return;
            }
        }
    }

    LOG.debug("Partition Key for: {} > {}", url, partitionKey);

    _collector.emit(tuple, new Values(url, partitionKey, metadata));
    _collector.ack(tuple);
}

From source file:com.digitalpebble.stormcrawler.bolt.URLPartitionerBolt.java

@Override
public void execute(Tuple tuple) {
    String url = tuple.getStringByField("url");
    Metadata metadata = null;//from   www . j  a v a2 s.  co  m

    if (tuple.contains("metadata"))
        metadata = (Metadata) tuple.getValueByField("metadata");

    // maybe there is a field metadata but it can be null
    // or there was no field at all
    if (metadata == null)
        metadata = Metadata.empty;

    String partitionKey = null;
    String host = "";

    // IP in metadata?
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP)) {
        String ip_provided = metadata.getFirstValue("ip");
        if (StringUtils.isNotBlank(ip_provided)) {
            partitionKey = ip_provided;
            eventCounter.scope("provided").incrBy(1);
        }
    }

    if (partitionKey == null) {
        URL u;
        try {
            u = new URL(url);
            host = u.getHost();
        } catch (MalformedURLException e1) {
            eventCounter.scope("Invalid URL").incrBy(1);
            LOG.warn("Invalid URL: {}", url);
            // ack it so that it doesn't get replayed
            _collector.ack(tuple);
            return;
        }
    }

    // partition by hostname
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_HOST))
        partitionKey = host;

    // partition by domain : needs fixing
    else if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_DOMAIN)) {
        partitionKey = PaidLevelDomain.getPLD(host);
    }

    // partition by IP
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP) && partitionKey == null) {
        // try to get it from cache first
        partitionKey = cache.get(host);
        if (partitionKey != null) {
            eventCounter.scope("from cache").incrBy(1);
        } else {
            try {
                long start = System.currentTimeMillis();
                final InetAddress addr = InetAddress.getByName(host);
                partitionKey = addr.getHostAddress();
                long end = System.currentTimeMillis();
                LOG.debug("Resolved IP {} in {} msec for : {}", partitionKey, end - start, url);

                // add to cache
                cache.put(host, partitionKey);

            } catch (final Exception e) {
                eventCounter.scope("Unable to resolve IP").incrBy(1);
                LOG.warn("Unable to resolve IP for: {}", host);
                _collector.ack(tuple);
                return;
            }
        }
    }

    LOG.debug("Partition Key for: {} > {}", url, partitionKey);

    _collector.emit(tuple, new Values(url, partitionKey, metadata));
    _collector.ack(tuple);
}

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

/**
 * Adds the address to the ban list of the login server, with the given duration.
 * //w  ww .  j a  v  a2 s. c  o m
 * @param address The Address to be banned.
 * @param duration is milliseconds
 */
public void addBanForAddress(InetAddress address, long duration) {
    SubNet _net = new SubNet(address.getHostAddress());
    if (duration != 0)
        _bannedIps.put(_net, new BanInfo(_net, System.currentTimeMillis() + duration));
    else
        _restrictedIps.put(_net, new BanInfo(_net, 0));
}

From source file:org.inaetics.pubsub.demo.config.Configurator.java

private String getIp() {
    try {/*from w ww  .  j  a v a 2s . c  o m*/
        Enumeration<NetworkInterface> nEnumeration = NetworkInterface.getNetworkInterfaces();
        while (nEnumeration.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) nEnumeration.nextElement();
            if (networkInterface.getName().equals("eth1")) {
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) addresses.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "localhost";
}

From source file:org.manalith.ircbot.plugin.ping.PingPlugin.java

@BotCommand("")
public String ping(@Option(name = "?", help = "?  ?? ? IP ") String uri) {
    InetAddress addr;

    try {/*from   w  w w . ja va  2 s  .  c om*/
        addr = InetAddress.getByName(uri);
    } catch (UnknownHostException e) {
        return "[Ping]   .";
    }

    try {
        return String.format("[Ping] %s(%s) is %s: ", addr.getHostName(), addr.getHostAddress(),
                addr.isReachable(3000) ? "reachable" : "not reachable");
    } catch (IOException e) {
        return String.format("[Ping] ?  ?.(%s)", e.getMessage());
    }
}