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.hs.mail.imap.server.ImapServer.java

public void afterPropertiesSet() throws Exception {
    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // Do not create many instances of Timer.
    // HashedWheelTimer creates a new thread whenever it is instantiated and
    // started. Therefore, you should make sure to create only one instance
    // and share it across your application.
    Timer timer = new HashedWheelTimer();
    // Set 30-minute read timeout.
    int timeout = (int) Config.getNumberProperty("imap_timeout", 1800);
    // timer must be shared.
    timeoutHandler = new ReadTimeoutHandler(timer, timeout);
    // prepare business logic handler
    handler = new ImapServerHandler();

    bootstrap.setPipelineFactory(createPipelineFactory());

    // Bind and start to accept incoming connections.
    InetSocketAddress endpoint = null;
    if (!StringUtils.isEmpty(bind) && !"*".equals(bind)) {
        InetAddress bindTo = InetAddress.getByName(bind);
        endpoint = new InetSocketAddress(bindTo, getPort());
    } else {//from www. ja v a2s  . c  o  m
        endpoint = new InetSocketAddress(getPort());
    }
    bootstrap.bind(endpoint);

    StringBuilder logBuffer = new StringBuilder(64).append(getServiceType()).append(" started on port ")
            .append(getPort());
    Logger.getLogger("console").info(logBuffer.toString());
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

@AfterClass
public static void after() throws Exception {
    final ModelControllerClient client = ModelControllerClient.Factory
            .create(InetAddress.getByName("localhost"), 9999);
    // and remove the connector again
    removeTestConnector(client);//  w w  w  .j  a v a  2s.  c  o m
    // remove test security domains
    removeSecurityDomains(client);
}

From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java

private HiveAuthentication.HiveAuthDetails createUserDetails(HttpServletRequest request)
        throws UnknownHostException {
    return new HiveAuthentication.HiveAuthDetails(InetAddress.getByName(request.getRemoteAddr()),
            request.getHeader(HttpHeaders.ORIGIN), request.getHeader(HttpHeaders.AUTHORIZATION));
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send reply.//from   w w  w. ja  v  a2  s  .c  o  m
 *
 * @param host the host
 * @param port the port
 * @param msg the msg
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void sendReply(String host, int port, String msg) {
    DatagramSocket datagramSocket = null;

    try {
        datagramSocket = new DatagramSocket();
        InetAddress inetAddr = InetAddress.getByName(host);
        DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port);

        logger.trace(
                "Sending this reply [" + host + ":" + port + "]: " + StringUtils.replace(msg, CRLF, "<CRLF>"));

        datagramSocket.send(dgmPacket);
    } catch (Exception e) {
        logger.info(e.getMessage());
        logger.debug("Error sending reply", e);
    } finally {
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdDevice> findIpv6Devices() throws IOException, InterruptedException {
    InetSocketAddress multicastSocketAddress;
    try {/*from w  ww  . java 2 s  . c o m*/
        multicastSocketAddress = new InetSocketAddress(InetAddress.getByName("ff02::c"), 1900); // NOPMD
    } catch (UnknownHostException uhe) {
        throw new IllegalStateException(uhe);
    }

    Set<InetAddress> localIpv6Addresses = NetworkUtils.getAllLocalIpv6Addresses();
    return scanForDevices(multicastSocketAddress, localIpv6Addresses, IPV6_SEARCH_QUERY);
}

From source file:BaseProperties.java

/**
 * Get <code>InetAddress</code>.
 *//*  www  .  j a v a 2 s . c o m*/
public InetAddress getInetAddress(final String str) throws Exception {
    String value = getProperty(str);
    if (value == null) {
        throw new Exception(str + " not found");
    }

    try {
        return InetAddress.getByName(value);
    } catch (UnknownHostException ex) {
        throw new Exception("Host " + value + " not found");
    }
}

From source file:SocketFetcher.java

/**
 * This method returns a Socket.  Properties control the use of
 * socket factories and other socket characteristics.  The properties
 * used are: <p>//from  w  ww. jav a  2 s . co m
 * <ul>
 * <li> <i>prefix</i>.socketFactory.class
 * <li> <i>prefix</i>.socketFactory.fallback
 * <li> <i>prefix</i>.socketFactory.port
 * <li> <i>prefix</i>.timeout
 * <li> <i>prefix</i>.connectiontimeout
 * <li> <i>prefix</i>.localaddress
 * <li> <i>prefix</i>.localport
 * </ul> <p>
 * If the socketFactory.class property isn't set, the socket
 * returned is an instance of java.net.Socket connected to the
 * given host and port. If the socketFactory.class property is set,
 * it is expected to contain a fully qualified classname of a
 * javax.net.SocketFactory subclass.  In this case, the class is
 * dynamically instantiated and a socket created by that
 * SocketFactory is returned. <p>
 *
 * If the socketFactory.fallback property is set to false, don't
 * fall back to using regular sockets if the socket factory fails. <p>
 *
 * The socketFactory.port specifies a port to use when connecting
 * through the socket factory.  If unset, the port argument will be
 * used.  <p>
 *
 * If the connectiontimeout property is set, we use a separate thread
 * to make the connection so that we can timeout that connection attempt.
 * <p>
 *
 * If the timeout property is set, it is used to set the socket timeout.
 * <p>
 *
 * If the localaddress property is set, it's used as the local address
 * to bind to.  If the localport property is also set, it's used as the
 * local port number to bind to.
 *
 * @param host The host to connect to
 * @param port The port to connect to at the host
 * @param props Properties object containing socket properties
 * @param prefix Property name prefix, e.g., "mail.imap"
 * @param useSSL use the SSL socket factory as the default
 */
public static Socket getSocket(String host, int port, Properties props, String prefix, boolean useSSL)
        throws IOException {

    if (prefix == null)
        prefix = "socket";
    if (props == null)
        props = new Properties(); // empty
    String s = props.getProperty(prefix + ".connectiontimeout", null);
    int cto = -1;
    if (s != null) {
        try {
            cto = Integer.parseInt(s);
        } catch (NumberFormatException nfex) {
        }
    }

    Socket socket = null;
    String timeout = props.getProperty(prefix + ".timeout", null);
    String localaddrstr = props.getProperty(prefix + ".localaddress", null);
    InetAddress localaddr = null;
    if (localaddrstr != null)
        localaddr = InetAddress.getByName(localaddrstr);
    String localportstr = props.getProperty(prefix + ".localport", null);
    int localport = 0;
    if (localportstr != null) {
        try {
            localport = Integer.parseInt(localportstr);
        } catch (NumberFormatException nfex) {
        }
    }

    boolean fb = false;
    String fallback = props.getProperty(prefix + ".socketFactory.fallback", null);
    fb = fallback == null || (!fallback.equalsIgnoreCase("false"));

    String sfClass = props.getProperty(prefix + ".socketFactory.class", null);
    int sfPort = -1;
    try {
        SocketFactory sf = getSocketFactory(sfClass);
        if (sf != null) {
            String sfPortStr = props.getProperty(prefix + ".socketFactory.port", null);
            if (sfPortStr != null) {
                try {
                    sfPort = Integer.parseInt(sfPortStr);
                } catch (NumberFormatException nfex) {
                }
            }

            // if port passed in via property isn't valid, use param
            if (sfPort == -1)
                sfPort = port;
            socket = createSocket(localaddr, localport, host, sfPort, cto, sf, useSSL);
        }
    } catch (SocketTimeoutException sex) {
        throw sex;
    } catch (Exception ex) {
        if (!fb) {
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t instanceof Exception)
                    ex = (Exception) t;
            }
            if (ex instanceof IOException)
                throw (IOException) ex;
            IOException ioex = new IOException("Couldn't connect using \"" + sfClass
                    + "\" socket factory to host, port: " + host + ", " + sfPort + "; Exception: " + ex);
            ioex.initCause(ex);
            throw ioex;
        }
    }

    if (socket == null)
        socket = createSocket(localaddr, localport, host, port, cto, null, useSSL);

    int to = -1;
    if (timeout != null) {
        try {
            to = Integer.parseInt(timeout);
        } catch (NumberFormatException nfex) {
        }
    }
    if (to >= 0)
        socket.setSoTimeout(to);

    configureSSLSocket(socket, props, prefix);
    return socket;
}

From source file:com.adobe.ags.curly.controller.AuthHandler.java

private void loginTest() {
    CloseableHttpClient client = null;//from w  w w .j a  va2s  .c om
    try {
        if (!model.requiredFieldsPresentProperty().get()) {
            Platform.runLater(() -> {
                model.loginConfirmedProperty().set(false);
                model.statusMessageProperty().set(ApplicationState.getMessage(INCOMPLETE_FIELDS));
            });
            return;
        }

        String url = getUrlBase() + TEST_PAGE;
        URL testUrl = new URL(url);
        InetAddress address = InetAddress.getByName(testUrl.getHost());
        if (address == null || isDnsRedirect(address)) {
            throw new UnknownHostException("Unknown host " + testUrl.getHost());
        }

        Platform.runLater(() -> {
            model.loginConfirmedProperty().set(false);
            model.statusMessageProperty().set(ApplicationState.getMessage(ATTEMPTING_CONNECTION));
        });
        client = getAuthenticatedClient();
        HttpGet loginTest = new HttpGet(url);
        HttpResponse response = client.execute(loginTest);
        StatusLine responseStatus = response.getStatusLine();

        if (responseStatus.getStatusCode() >= 200 && responseStatus.getStatusCode() < 300) {
            Platform.runLater(() -> {
                model.loginConfirmedProperty().set(true);
                model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_SUCCESSFUL));
            });
        } else {
            Platform.runLater(() -> {
                model.loginConfirmedProperty().set(false);
                model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR)
                        + responseStatus.getReasonPhrase() + " (" + responseStatus.getStatusCode() + ")");
            });
        }
    } catch (MalformedURLException | IllegalArgumentException | UnknownHostException ex) {
        Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
        Platform.runLater(() -> {
            model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + ex.getMessage());
            model.loginConfirmedProperty().set(false);
        });
    } catch (Throwable ex) {
        Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
        Platform.runLater(() -> {
            model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + ex.getMessage());
            model.loginConfirmedProperty().set(false);
        });
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException ex) {
                Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:net.fenyo.mail4hotspot.service.HttpProxy.java

public int connect() throws IOException {
    last_use = System.currentTimeMillis();

    // log.debug("connect(): new Socket()");
    // final InetAddress address = InetAddress.getByAddress("xyz", new byte [] { (byte) 192, (byte) 168, (byte) 0, (byte) 5 /* 19 */ } );
    final InetAddress address = InetAddress.getByName(remote_host);
    final SocketAddress s_address = new InetSocketAddress(address, remote_port);
    socket_channel = SocketChannel.open();
    socket_channel.configureBlocking(true);
    socket_channel.connect(s_address);/*from   w ww  .  ja  v a 2  s. c  o  m*/
    socket_channel.configureBlocking(false);
    // log.debug("local port: " + ((InetSocketAddress) socket_channel.getLocalAddress()).getPort());

    local_port = ((InetSocketAddress) socket_channel.getLocalAddress()).getPort();

    return local_port;
}

From source file:org.apache.smscserver.config.spring.SpringUtil.java

/**
 * Return an attribute value as an {@link InetAddress}
 * /* w w  w  .  j  a v  a 2s. c  om*/
 * @param parent
 *            The element
 * @param attrName
 *            The attribute name
 * @return The attribute value parsed into a {@link InetAddress}
 */
public static InetAddress parseInetAddress(final Element parent, final String attrName) {
    if (StringUtils.hasText(parent.getAttribute(attrName))) {
        try {
            return InetAddress.getByName(parent.getAttribute(attrName));
        } catch (UnknownHostException e) {
            throw new SmscServerConfigurationException("Unknown host", e);
        }
    }
    return null;
}