Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

In this page you can find the example usage for java.net InetAddress getByName.

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:com.googlecode.psiprobe.controllers.WhoisController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List lines = null;/*  www  .  ja  v a2  s.c om*/
    boolean timeout = false;
    String reverseName = null;

    String theIP = ServletRequestUtils.getStringParameter(request, "ip", null);

    Whois.Response wh = null;
    try {
        wh = Whois.lookup(getDefaultServer(), getDefaultPort(), theIP, getLookupTimeout());
    } catch (IOException e) {
        timeout = true;
    }

    if (wh != null) {
        lines = new ArrayList(50);
        BufferedReader br = new BufferedReader(
                new InputStreamReader(new ByteArrayInputStream(wh.getSummary().getBytes())));
        try {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } finally {
            br.close();
        }
    }

    if (theIP != null) {
        try {
            reverseName = InetAddress.getByName(theIP).getCanonicalHostName();
        } catch (UnknownHostException e) {
            logger.error("could not run a DNS query on " + theIP);
        }
    }
    return new ModelAndView(getViewName(), "result", lines).addObject("timeout", Boolean.valueOf(timeout))
            .addObject("whoisServer",
                    wh != null ? wh.getServer() + ":" + wh.getPort() : defaultServer + ":" + defaultPort)
            .addObject("domainName", reverseName);
}

From source file:com.streamsets.pipeline.stage.processor.geolocation.TestGeolocationProcessor.java

@Test
public void testConversion() throws Exception {
    String[] ips = { "128.101.101.101", "8.8.8.8" };
    for (String ipAsString : ips) {
        InetAddress ip = InetAddress.getByName(ipAsString);
        byte[] ipAsBytes = ip.getAddress();
        int ipAsInt = GeolocationProcessor.ipAsBytesToInt(ipAsBytes);
        Assert.assertArrayEquals(ipAsBytes, GeolocationProcessor.ipAsIntToBytes(ipAsInt));
        Assert.assertArrayEquals(ipAsBytes, GeolocationProcessor.ipAsStringToBytes(ipAsString));
        Assert.assertEquals(ipAsString, GeolocationProcessor.ipAsIntToString(ipAsInt));
        Assert.assertEquals(ipAsString, GeolocationProcessor.ipAsIntToString(ipAsInt));
        Assert.assertEquals(ipAsInt, GeolocationProcessor.ipAsStringToInt(ipAsString));
        Assert.assertArrayEquals(ipAsBytes, GeolocationProcessor.ipAsStringToBytes(ipAsString));
    }/*from  w  w w.  j a va2  s. co  m*/
}

From source file:net.majorkernelpanic.streaming.misc.UriParser.java

/**
 * Configures a Session according to the given URI.
 * Here are some examples of URIs that can be used to configure a Session:
 * <ul><li>rtsp://xxx.xxx.xxx.xxx:8086?h264&flash=on</li>
 * <li>rtsp://xxx.xxx.xxx.xxx:8086?h263&camera=front&flash=on</li>
 * <li>rtsp://xxx.xxx.xxx.xxx:8086?h264=200-20-320-240</li>
 * <li>rtsp://xxx.xxx.xxx.xxx:8086?aac</li></ul>
 * @param uri The URI//w ww .  ja va  2  s.c  om
 * @param session The Session that will be configured
 * @throws IllegalStateException
 * @throws IOException
 */
public static void parse(String uri, Session session) throws IllegalStateException, IOException {
    boolean flash = false;
    int camera = CameraInfo.CAMERA_FACING_BACK;

    List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri), "UTF-8");
    if (params.size() > 0) {

        // Those parameters must be parsed first or else they won't necessarily be taken into account
        for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
            NameValuePair param = it.next();

            // FLASH ON/OFF
            if (param.getName().equals("flash")) {
                if (param.getValue().equals("on"))
                    flash = true;
                else
                    flash = false;
            }

            // CAMERA -> the client can choose between the front facing camera and the back facing camera
            else if (param.getName().equals("camera")) {
                if (param.getValue().equals("back"))
                    camera = CameraInfo.CAMERA_FACING_BACK;
                else if (param.getValue().equals("front"))
                    camera = CameraInfo.CAMERA_FACING_FRONT;
            }

            // MULTICAST -> the stream will be sent to a multicast group
            // The default mutlicast address is 228.5.6.7, but the client can specify one 
            else if (param.getName().equals("multicast")) {
                session.setRoutingScheme(Session.MULTICAST);
                if (param.getValue() != null) {
                    try {
                        InetAddress addr = InetAddress.getByName(param.getValue());
                        if (!addr.isMulticastAddress()) {
                            throw new IllegalStateException("Invalid multicast address !");
                        }
                        session.setDestination(addr);
                    } catch (UnknownHostException e) {
                        throw new IllegalStateException("Invalid multicast address !");
                    }
                } else {
                    // Default multicast address
                    session.setDestination(InetAddress.getByName("228.5.6.7"));
                }
            }

            // UNICAST -> the client can use this so specify where he wants the stream to be sent
            else if (param.getName().equals("unicast")) {
                if (param.getValue() != null) {
                    try {
                        InetAddress addr = InetAddress.getByName(param.getValue());
                        session.setDestination(addr);
                    } catch (UnknownHostException e) {
                        throw new IllegalStateException("Invalid destination address !");
                    }
                }
            }

            // TTL -> the client can modify the time to live of packets
            // By default ttl=64
            else if (param.getName().equals("ttl")) {
                if (param.getValue() != null) {
                    try {
                        int ttl = Integer.parseInt(param.getValue());
                        if (ttl < 0)
                            throw new IllegalStateException("The TTL must be a positive integer !");
                        session.setTimeToLive(ttl);
                    } catch (Exception e) {
                        throw new IllegalStateException("The TTL must be a positive integer !");
                    }
                }
            }

            // No tracks will be added to the session
            else if (param.getName().equals("stop")) {
                return;
            }

        }

        for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
            NameValuePair param = it.next();

            // H264
            if (param.getName().equals("h264")) {
                VideoQuality quality = VideoQuality.parseQuality(param.getValue());
                session.addVideoTrack(Session.VIDEO_H264, camera, quality, flash);
            }

            // H263
            else if (param.getName().equals("h263")) {
                VideoQuality quality = VideoQuality.parseQuality(param.getValue());
                session.addVideoTrack(Session.VIDEO_H263, camera, quality, flash);
            }

            // AMRNB
            else if (param.getName().equals("amrnb") || param.getName().equals("amr")) {
                session.addAudioTrack(Session.AUDIO_AMRNB);
            }

            // AAC
            else if (param.getName().equals("aac")) {
                session.addAudioTrack(Session.AUDIO_AAC);
            }

            // Generic Audio Stream -> make use of api level 12
            // TODO: Doesn't work :/
            else if (param.getName().equals("testnewapi")) {
                session.addAudioTrack(Session.AUDIO_ANDROID_AMR);
            }

        }

        // The default behavior is to only add one video track
        if (session.getTrackCount() == 0) {
            session.addVideoTrack();
            session.addAudioTrack();
        }

    }
    // Uri has no parameters: the default behavior is to only add one video track
    else {
        session.addVideoTrack();
        session.addAudioTrack();
    }
}

From source file:com.navercorp.pinpoint.collector.receiver.udp.BaseUDPHandlerFactory.java

private InetAddress[] setIgnoreAddressList(List<String> l4IpList) {
    if (l4IpList == null) {
        return null;
    }//from  ww  w  . jav a 2s.c  om
    try {
        List<InetAddress> inetAddressList = new ArrayList<InetAddress>();
        for (int i = 0; i < l4IpList.size(); i++) {
            String l4Ip = l4IpList.get(i);
            if (StringUtils.isBlank(l4Ip)) {
                continue;
            }

            InetAddress address = InetAddress.getByName(l4Ip);
            if (address != null) {
                inetAddressList.add(address);
            }
        }

        InetAddress[] inetAddressArray = new InetAddress[inetAddressList.size()];
        return inetAddressList.toArray(inetAddressArray);
    } catch (UnknownHostException e) {
        logger.warn("l4ipList error {}", l4IpList, e);
    }

    return null;
}

From source file:ac.dynam.rundeck.plugin.resources.ovirt.InstanceToNodeMapper.java

/**
 * Convert an oVirt Instance to a RunDeck INodeEntry based on the mapping input
 *//*from w ww.jav  a  2  s .  c o  m*/
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final VM inst) throws GeneratorException {
    final NodeEntryImpl node = new NodeEntryImpl();

    node.setNodename(inst.getName());
    node.setOsArch(inst.getCpu().getArchitecture());
    node.setOsName(inst.getOs().getType());
    node.setDescription(inst.getDescription());
    node.setUsername("root");
    InetAddress address = null;
    if (inst.getGuestInfo() != null) {
        try {
            address = InetAddress.getByName(inst.getGuestInfo().getFqdn());
            logger.debug("Host " + node.getNodename() + " Guest FQDN " + inst.getGuestInfo().getFqdn()
                    + " Address: " + address.getHostName());
            if (address.getHostName() == "localhost")
                throw new UnknownHostException();
        } catch (UnknownHostException e) {
            /* try the first IP instead then */
            logger.warn("Host " + node.getNodename() + " address " + inst.getGuestInfo().getFqdn()
                    + " does not resolve. Trying IP addresses instead");
            for (int i = 0; i < inst.getGuestInfo().getIps().getIPs().size(); i++) {
                logger.debug("Host " + node.getNodename() + " Trying "
                        + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                try {
                    address = InetAddress.getByName(inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                    if (address != null) {
                        if (address.isLinkLocalAddress() || address.isMulticastAddress()) {
                            logger.warn("Host " + node.getNodename() + " ip address is not valid: "
                                    + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                            continue;
                        }
                        logger.debug("Host " + node.getNodename() + " ip address " + address.getHostAddress()
                                + " will be used instead");
                        break;
                    }
                } catch (UnknownHostException e1) {
                    logger.warn("Host " + node.getNodename() + " IP Address "
                            + inst.getGuestInfo().getIps().getIPs().get(i).getAddress() + " is invalid");
                }
            }
        }
    }
    if (address == null) {
        /* try resolving based on name */
        try {
            address = InetAddress.getByName(node.getNodename());
        } catch (UnknownHostException e) {
            logger.warn("Unable to Find IP address for Host " + node.getNodename());
            return null;
        }
    }

    if (address != null)
        node.setHostname(address.getCanonicalHostName());

    if (inst.getTags() != null) {
        VMTags tags = inst.getTags();
        final HashSet<String> tagset = new HashSet<String>();
        try {
            for (int j = 0; j < tags.list().size(); j++) {
                tagset.add(tags.list().get(j).getName());
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null == node.getTags()) {
            node.setTags(tagset);
        } else {
            final HashSet<String> orig = new HashSet<String>(node.getTags());
            orig.addAll(tagset);
            node.setTags(orig);
        }
    }

    if (inst.getHighAvailability().getEnabled())
        node.setAttribute("HighAvailability", "true");
    if (inst.getType() != null)
        node.setAttribute("Host Type", inst.getType());
    node.setAttribute("oVirt VM", "true");
    node.setAttribute("oVirt Host", inst.getHost().getName());

    return node;
}

From source file:com.nubits.nubot.NTP.NTPClient.java

private Date getTimeImpl(String host) throws IOException {
    Date toRet;// w w  w.  j  av  a  2 s .c om
    TimeUDPClient client = new TimeUDPClient();
    // We want to timeout if a response takes longer than TIMEOUT seconds
    client.setDefaultTimeout(TIMEOUT);
    client.open();
    toRet = client.getDate(InetAddress.getByName(host));
    client.close();

    return toRet;
}

From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java

@SuppressWarnings("TryWithIdenticalCatches")
protected static boolean checkRouteToHost(Context context, String host, boolean usingMmsRadio)
        throws IOException {
    InetAddress inetAddress = InetAddress.getByName(host);
    if (!usingMmsRadio) {
        if (inetAddress.isSiteLocalAddress()) {
            throw new IOException("RFC1918 address in non-MMS radio situation!");
        }/* w ww .  ja  va 2s .com*/
        Log.w(TAG, "returning vacuous success since MMS radio is not in use");
        return true;
    }

    if (inetAddress == null) {
        throw new IOException("Unable to lookup host: InetAddress.getByName() returned null.");
    }

    byte[] ipAddressBytes = inetAddress.getAddress();
    if (ipAddressBytes == null) {
        Log.w(TAG, "resolved IP address bytes are null, returning true to attempt a connection anyway.");
        return true;
    }

    Log.w(TAG, "Checking route to address: " + host + ", " + inetAddress.getHostAddress());
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        final Method requestRouteMethod = manager.getClass().getMethod("requestRouteToHostAddress",
                Integer.TYPE, InetAddress.class);
        final boolean routeToHostObtained = (Boolean) requestRouteMethod.invoke(manager,
                MmsRadio.TYPE_MOBILE_MMS, inetAddress);
        Log.w(TAG, "requestRouteToHostAddress(" + inetAddress + ") -> " + routeToHostObtained);
        return routeToHostObtained;
    } catch (NoSuchMethodException nsme) {
        Log.w(TAG, nsme);
    } catch (IllegalAccessException iae) {
        Log.w(TAG, iae);
    } catch (InvocationTargetException ite) {
        Log.w(TAG, ite);
    }

    final int ipAddress = Conversions.byteArrayToIntLittleEndian(ipAddressBytes, 0);
    final boolean routeToHostObtained = manager.requestRouteToHost(MmsRadio.TYPE_MOBILE_MMS, ipAddress);
    Log.w(TAG, "requestRouteToHost(" + ipAddress + ") -> " + routeToHostObtained);
    return routeToHostObtained;
}

From source file:com.digitalpebble.stormcrawler.util.URLPartitioner.java

/**
 * Returns the host, domain, IP of a URL so that it can be partitioned for
 * politeness/*  w  ww. j av a2  s  .  c  o m*/
 **/
public String getPartition(String url, Metadata metadata) {

    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;
        }
    }

    if (partitionKey == null) {
        URL u;
        try {
            u = new URL(url);
            host = u.getHost();
        } catch (MalformedURLException e1) {
            LOG.warn("Invalid URL: {}", url);
            return null;
        }
    }

    // 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 {
            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);
        } catch (final Exception e) {
            LOG.warn("Unable to resolve IP for: {}", host);
            return null;
        }
    }

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

    return partitionKey;
}

From source file:com.digitalpebble.storm.crawler.util.URLPartitioner.java

/**
 * Returns the host, domain, IP of a URL so that it can be partitioned for
 * politeness/*from  ww  w  .  j  ava  2s . c  om*/
 **/
public String getPartition(String url, Metadata metadata) {

    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;
        }
    }

    if (partitionKey == null) {
        URL u;
        try {
            u = new URL(url);
            host = u.getHost();
        } catch (MalformedURLException e1) {
            LOG.warn("Invalid URL: {}", url);
            return null;
        }
    }

    // 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 {
            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);
        } catch (final Exception e) {
            LOG.warn("Unable to resolve IP for: {}", host);
            return null;
        }
    }

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

    return partitionKey;
}

From source file:com.predic8.membrane.core.interceptor.acl.Resource.java

public boolean checkAccess(String hostname, String ip) {
    if (log.isDebugEnabled()) {
        log.debug("Hostname: " + hostname
                + (router.getTransport().isReverseDNS() ? "" : " (reverse DNS is disabled in configuration)"));
        log.debug("IP: " + ip);
        try {//from w w w .  ja  va2  s . c  o m
            log.debug("Hostaddress (might require slow DNS lookup): "
                    + router.getDnsCache().getHostName(InetAddress.getByName(ip)));
        } catch (UnknownHostException e) {
            log.debug("Failed to get hostname from address: " + e.getMessage());
        }
    }

    for (AbstractClientAddress cAdd : clientAddresses) {
        if (cAdd.matches(hostname, ip))
            return true;
    }

    return false;
}