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:eu.unifiedviews.plugins.extractor.filesdownload.ReflectionSocketFactory.java

/**
 * This method attempts to execute Socket method available since Java 1.4
 * using reflection. If the methods are not available or could not be executed <tt>null</tt> is returned
 * //from   www. j a v  a  2 s.com
 * @param socketfactoryName
 *            name of the socket factory class
 * @param host
 *            the host name/IP
 * @param port
 *            the port on the host
 * @param localAddress
 *            the local host name/IP to bind the socket to
 * @param localPort
 *            the port on the local machine
 * @param timeout
 *            the timeout value to be used in milliseconds. If the socket cannot be
 *            completed within the given time limit, it will be abandoned
 * @return a connected Socket
 * @throws IOException
 *             if an I/O error occurs while creating the socket
 * @throws UnknownHostException
 *             if the IP address of the host cannot be
 *             determined
 * @throws ConnectTimeoutException
 *             if socket cannot be connected within the
 *             given time limit
 */
public static Socket createSocket(final Object socketfactory, final String host, final int port,
        final InetAddress localAddress, final int localPort, int timeout)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (REFLECTION_FAILED) {
        //This is known to have failed before. Do not try it again
        return null;
    }
    // This code uses reflection to essentially do the following:
    //
    //  SocketFactory socketFactory = Class.forName(socketfactoryName).getDefault();
    //  Socket socket = socketFactory.createSocket();
    //  SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    //  SocketAddress remoteaddr = new InetSocketAddress(host, port);
    //  socket.bind(localaddr);
    //  socket.connect(remoteaddr, timeout);
    //  return socket;
    try {
        Class socketfactoryClass = socketfactory.getClass();//Class.forName(socketfactoryName);
        Method method = socketfactoryClass.getMethod("getDefault", new Class[] {});
        //            Object socketfactory = method.invoke(null, 
        //                new Object[] {});
        method = socketfactoryClass.getMethod("createSocket", new Class[] {});
        Socket socket = (Socket) method.invoke(socketfactory, new Object[] {});

        if (INETSOCKETADDRESS_CONSTRUCTOR == null) {
            Class addressClass = Class.forName("java.net.InetSocketAddress");
            INETSOCKETADDRESS_CONSTRUCTOR = addressClass
                    .getConstructor(new Class[] { InetAddress.class, Integer.TYPE });
        }

        Object remoteaddr = INETSOCKETADDRESS_CONSTRUCTOR
                .newInstance(new Object[] { InetAddress.getByName(host), new Integer(port) });

        Object localaddr = INETSOCKETADDRESS_CONSTRUCTOR
                .newInstance(new Object[] { localAddress, new Integer(localPort) });

        if (SOCKETCONNECT_METHOD == null) {
            SOCKETCONNECT_METHOD = Socket.class.getMethod("connect",
                    new Class[] { Class.forName("java.net.SocketAddress"), Integer.TYPE });
        }

        if (SOCKETBIND_METHOD == null) {
            SOCKETBIND_METHOD = Socket.class.getMethod("bind",
                    new Class[] { Class.forName("java.net.SocketAddress") });
        }
        SOCKETBIND_METHOD.invoke(socket, new Object[] { localaddr });
        SOCKETCONNECT_METHOD.invoke(socket, new Object[] { remoteaddr, new Integer(timeout) });
        return socket;
    } catch (InvocationTargetException e) {
        Throwable cause = e.getTargetException();
        if (SOCKETTIMEOUTEXCEPTION_CLASS == null) {
            try {
                SOCKETTIMEOUTEXCEPTION_CLASS = Class.forName("java.net.SocketTimeoutException");
            } catch (ClassNotFoundException ex) {
                // At this point this should never happen. Really.
                REFLECTION_FAILED = true;
                return null;
            }
        }
        if (SOCKETTIMEOUTEXCEPTION_CLASS.isInstance(cause)) {
            throw new ConnectTimeoutException(
                    "The host did not accept the connection within timeout of " + timeout + " ms", cause);
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        return null;
    } catch (Exception e) {
        REFLECTION_FAILED = true;
        return null;
    }
}

From source file:net.itransformers.idiscover.discoveryhelpers.xml.SnmpForXslt.java

public static String getNameByDNS(String ipAddress) {
    if (mockSnmpForXslt != null) {
        return mockSnmpForXslt.getNameByDNS(ipAddress);
    }/*from www  .  jav a  2s  .  co  m*/

    //        InetAddress inetAddress = new InetAddress();
    InetAddress address = null;
    try {
        address = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    return address.getHostAddress();

}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {/*www . j  a v  a 2  s.c  o  m*/
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go
                if (packet.remaining() < 4
                        || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) {
                    return;
                }

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                ByteBuffer outBuf = ByteBuffer.allocate(1100);
                MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0,
                        InetAddress.getByName("::"), 0L);
                mpr.dump(outBuf, bindMap.get(channel));
                outBuf.flip();

                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:ch.cyberduck.core.socket.NetworkInterfaceAwareSocketFactory.java

@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddr, final int localPort)
        throws IOException {
    return this.createSocket(InetAddress.getByName(host), port, localAddr, localPort);
}

From source file:it.jnrpe.server.CBindingThread.java

private void init() throws IOException, KeyManagementException, KeyStoreException, CertificateException,
        UnrecoverableKeyException {
    InetAddress addr = InetAddress.getByName(m_Binding.getIP());
    ServerSocketFactory sf = null;

    if (m_Binding.useSSL())
        sf = getSSLSocketFactory(m_Binding.getKeyStoreFile(), m_Binding.getKeyStorePassword(), "JKS");
    else/*from  w  w w .j a  v  a 2s.  co m*/
        sf = ServerSocketFactory.getDefault();

    m_serverSocket = sf.createServerSocket(m_Binding.getPort(), 0, addr);
    //m_serverSocket.setSoTimeout(10000); //Ten seconds timeout added by oriol.lopez
    if (m_serverSocket instanceof SSLServerSocket)
        ((SSLServerSocket) m_serverSocket)
                .setEnabledCipherSuites(((SSLServerSocket) m_serverSocket).getSupportedCipherSuites());

    // Init the thread factory
    m_threadFactory = new CThreadFactory(m_Binding.getThreadFactoryConfig());
}

From source file:fr.enseirb.odroidx.videomanager.Uploader.java

public void doUpload(Uri myFile) {
    createNotification();//from   ww  w  . j a va 2 s.  c o m
    File f = new File(myFile.getPath());
    SendName(f.getName().replace(' ', '-'));
    Log.e(getClass().getSimpleName(), "test: " + f.exists());
    if (f.exists()) {
        Socket s;
        try {
            Log.e(getClass().getSimpleName(), "test: " + server_ip);
            s = new Socket(InetAddress.getByName(server_ip), 5088);// Bug
            // using
            // variable
            // port
            OutputStream fluxsortie = s.getOutputStream();
            int nb_parts = (int) (f.length() / PART_SIZE);

            InputStream in = new BufferedInputStream(new FileInputStream(f));
            ByteArrayOutputStream byte_array = new ByteArrayOutputStream();
            BufferedOutputStream buffer = new BufferedOutputStream(byte_array);

            byte[] to_write = new byte[PART_SIZE];
            for (int i = 0; i < nb_parts; i++) {
                in.read(to_write, 0, PART_SIZE);
                buffer.write(to_write);
                buffer.flush();
                fluxsortie.write(byte_array.toByteArray());
                byte_array.reset();
                if ((i % 250) == 0) {
                    mBuilder.setProgress(nb_parts, i, false);
                    mNotifyManager.notify(NOTIFY_ID, mBuilder.getNotification());
                }
            }
            int remaining = (int) (f.length() - nb_parts * PART_SIZE);
            in.read(to_write, 0, remaining);
            buffer.write(to_write);
            buffer.flush();
            fluxsortie.write(byte_array.toByteArray());
            byte_array.reset();
            buffer.close();
            fluxsortie.close();
            in.close();
            s.close();
        } catch (ConnectException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        } catch (UnknownHostException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = UNKNOWN;
            Log.i(getClass().getSimpleName(), "Unknown host");
            e.printStackTrace();
        } catch (IOException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        }
    }
}

From source file:edu.ku.brc.specify.utilapps.RegProcEntry.java

private void discoverHostName() {
    if (hostName == null) {
        String ip = props.getProperty("ip");
        if (ip == null) {
            ip = "";
            hostName = "";
            props.put("hostname", hostName);
        } else {//from   w w w. j a  v a2  s . com
            hostName = ipHash.get(ip);
        }
        if (hostName == null) {
            try {
                InetAddress addr = InetAddress.getByName(ip);
                hostName = addr.getHostName();
                ipHash.put(ip, hostName);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        props.put("hostname", hostName);
    }
}

From source file:net.easymfne.personalmotd.PersonalMotd.java

/**
 * Load the saved address map from file.
 *///from w  ww . ja v a2  s.  c o m
private void loadAddressMap() {
    addressMap = new HashMap<InetAddress, String>();
    if (addressMapFile.exists() && addressMapFile.isFile()) {
        YamlConfiguration addressConfig = YamlConfiguration.loadConfiguration(addressMapFile);
        for (String a : addressConfig.getKeys(false)) {
            ConfigurationSection csA = addressConfig.getConfigurationSection(a);
            for (String b : csA.getKeys(false)) {
                ConfigurationSection csB = csA.getConfigurationSection(b);
                for (String c : csB.getKeys(false)) {
                    ConfigurationSection csC = csB.getConfigurationSection(c);
                    for (String d : csC.getKeys(false)) {
                        String address = StringUtils.join(new String[] { a, b, c, d }, ".");
                        String playerId = csC.getString(d);
                        try {
                            addressMap.put(InetAddress.getByName(address), playerId);
                        } catch (UnknownHostException e) {
                            fancyLog(Level.WARNING, "Unknown host: " + address + " (" + playerId + ")");
                        }
                    }
                }
            }
        }
    }
}

From source file:net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory.java

/**
 * peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446, multicastPacketTimeToLive=255
 *///from  w  ww .  j  a  va  2  s. co m
protected CacheManagerPeerProvider createAutomaticallyConfiguredCachePeerProvider(CacheManager cacheManager,
        Properties properties) throws IOException {
    String groupAddressString = PropertyUtil.extractAndLogProperty(MULTICAST_GROUP_ADDRESS, properties);
    InetAddress groupAddress = InetAddress.getByName(groupAddressString);
    String multicastPortString = PropertyUtil.extractAndLogProperty(MULTICAST_GROUP_PORT, properties);
    Integer multicastPort = new Integer(multicastPortString);
    String packetTimeToLiveString = PropertyUtil.extractAndLogProperty(MULTICAST_PACKET_TTL, properties);
    Integer timeToLive;
    if (packetTimeToLiveString == null) {
        timeToLive = new Integer(1);
        LOG.debug(
                "No TTL set. Setting it to the default of 1, which means packets are limited to the same subnet.");
    } else {
        timeToLive = new Integer(packetTimeToLiveString);
        if (timeToLive.intValue() < 0 || timeToLive.intValue() > MAXIMUM_TTL) {
            throw new CacheException("The TTL must be set to a value between 0 and 255");
        }
    }
    return new MulticastRMICacheManagerPeerProvider(cacheManager, groupAddress, multicastPort, timeToLive);
}

From source file:org.dd4t.core.util.HttpUtils.java

/**
 * Checking for local ip addresses, e.g.
 * <p/>//  w w w  . ja v  a  2  s.co  m
 * <pre>
 *     10.x.x.x
 *     172.[16-31].x.x
 *     192.168.x.x
 *     127.0.0.1
 * </pre>
 */
private static boolean isLocalDomainAddress(final String ipAddress) throws UnknownHostException {
    final InetAddress inetAddress = InetAddress.getByName(ipAddress);
    return inetAddress.isAnyLocalAddress() || inetAddress.isLinkLocalAddress()
            || inetAddress.isMulticastAddress() || inetAddress.isSiteLocalAddress();
}