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.predic8.membrane.core.transport.http.HttpEndpointListener.java

public HttpEndpointListener(String ip, int port, HttpTransport transport, SSLProvider sslProvider)
        throws IOException {
    this.transport = transport;
    this.sslProvider = sslProvider;

    try {/*from   ww  w. ja  va  2s . c o m*/
        if (sslProvider != null)
            serverSocket = sslProvider.createServerSocket(port, 50,
                    ip != null ? InetAddress.getByName(ip) : null);
        else
            serverSocket = new ServerSocket(port, 50, ip != null ? InetAddress.getByName(ip) : null);

        setName("Connection Acceptor " + (ip != null ? ip + ":" : ":") + port);
        log.debug("listening at port " + port + (ip != null ? " ip " + ip : ""));
    } catch (BindException e) {
        throw new PortOccupiedException(port);
    }
}

From source file:ch.cyberduck.core.bonjour.LimitedRendezvousListener.java

@Override
public void serviceResolved(final String identifier, final Host host) {
    if (log.isInfoEnabled()) {
        log.info(String.format("Service resolved with identifier %s with %s", identifier, host));
    }/*w w w. j a  va 2 s . co m*/
    if (PreferencesFactory.get().getBoolean("rendezvous.loopback.suppress")) {
        try {
            if (InetAddress.getByName(host.getHostname()).equals(InetAddress.getLocalHost())) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Suppressed Rendezvous notification for %s", host));
                }
                return;
            }
        } catch (UnknownHostException e) {
            //Ignore
        }
    }
    if (this.acquire()) {
        for (RendezvousListener listener : listeners) {
            listener.serviceResolved(identifier, host);
        }
    }
}

From source file:net.darkmist.clf.LogParserTest.java

public void testSimpleLog() throws Exception {
    String in = "1.2.3.4 Ident User [" + LOG_TIME_AS_STR + "] \"GET http://localhost:80/ HTTP/1.1\" 200 2";
    LogEntry entry = parser.parse(in);//w  w w  .  ja va 2 s . co m

    assertEquals(InetAddress.getByName("1.2.3.4"), entry.getIP());
    assertEquals("Ident", entry.getIdent());
    assertEquals("User", entry.getUser());
    assertEquals(LOG_TIME_AS_DATE, entry.getDate());
    assertEquals("GET", entry.getMethod());
    assertEquals("http://localhost:80/", entry.getURI());
    assertEquals("HTTP/1.1", entry.getProtocol());
    assertEquals(200, entry.getStatus());
    assertEquals(2, entry.getSize());
}

From source file:ru.asmsoft.p2p.outgoing.OutgoingChannelAdapter.java

public void send(Message<String> message) throws IOException {

    int port = (Integer) message.getHeaders().get("ip_port");
    String ip = (String) message.getHeaders().get("ip_address");
    byte[] bytesToSend = message.getPayload().getBytes();

    InetAddress IPAddress = InetAddress.getByName(ip);

    DatagramPacket sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length, IPAddress, port);
    clientSocket.send(sendPacket);/*from   w  ww.j  av  a 2s.  c om*/

}

From source file:com.DSC.client.SecureChannel.java

/**
 * Gets the date time offset for the client using a NTP server
 * @throws IOException //from w w  w .j  a v  a2s. co  m
 */
private static long getTimeOffset() throws IOException {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(NTP_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    return DateTimeUtils.currentTimeMillis() - timeInfo.getReturnTime();
}

From source file:se.kth.csc.controller.HomeController.java

/**
 * The welcome page of the web application
 *///from www. ja  va  2 s.com
@Order(Ordered.LOWEST_PRECEDENCE - 1000)
@RequestMapping(value = { "/", "/about", "/help", "/queue/**", "/admin" }, method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request) {

    String hostname;
    try {
        hostname = InetAddress.getByName(request.getRemoteHost()).getCanonicalHostName();
    } catch (UnknownHostException e) {
        log.error("Hostname error", e);
        hostname = null;
    }

    return new ModelAndView("index", "hostname", hostname);
}

From source file:com.stimulus.archiva.domain.Agent.java

public boolean isAllowed(InetAddress address) {

    // if nothing defined, by default we allow
    if (allowIPAddress.size() == 0)
        return true;

    for (String ip : allowIPAddress) {
        try {//from  w  w  w  .ja v a2 s.  com
            InetAddress newip = InetAddress.getByName(ip);
            if (newip.equals(address))
                return true;
        } catch (UnknownHostException uhe) {
            logger.debug("allowed agent ip address appears invalid");

        }
    }
    return false;
}

From source file:com.olacabs.fabric.executor.impl.HttpMetadataSource.java

@Override
public ComputationSpec load(String url) throws Exception {
    //First resolve to a real host-port combo if it's Mesos DNS
    String specEndpoint = url;//from w ww  .  j a v  a 2 s  .  c  om
    String specHost = specEndpoint.split("//")[1].split("/")[0];

    if (specHost.endsWith(".")) {
        // Need to do a srv record resolution
        List<LookupResult> results = dnsResolver.dnsSrvLookup(specHost);

        if (!results.isEmpty()) {
            specHost = InetAddress.getByName(results.get(0).host()).getHostAddress() + ":"
                    + results.get(0).port();
            LOGGER.info("Setting spec host to: " + specHost);
        } else {
            throw new RuntimeException(String.format("Dns Srv Resolution for spec host failed: %s", specHost));
        }
        specEndpoint = specEndpoint.split("//")[0] + "//" + specHost + "/"
                + specEndpoint.split("//")[1].replaceFirst(".*\\./", "");
    }
    HttpGet getRequest = new HttpGet(specEndpoint);
    HttpResponse response = httpClient.execute(getRequest);
    if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
        throw new Exception("Received: " + response.getStatusLine().getStatusCode() + " from spec url: " + url);
    }

    return mapper.readValue(EntityUtils.toByteArray(response.getEntity()), ComputationSpec.class);
}

From source file:com.t_oster.visicut.misc.Helper.java

public static List<String> findVisiCamInstances() {
    List<String> result = new LinkedList<String>();
    // Find the server using UDP broadcast
    try {//www  .  j a  v  a2 s . c  o  m
        //Open a random port to send the package
        DatagramSocket c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "VisiCamDiscover".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 8888);
            c.send(sendPacket);
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }
                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }
            }
        }
        //Wait for a response
        byte[] recvBuf = new byte[15000];
        c.setSoTimeout(3000);
        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
            try {
                c.receive(receivePacket);
                //Check if the message is correct
                String message = new String(receivePacket.getData()).trim();
                //Close the port!
                c.close();
                if (message.startsWith("http")) {
                    result.add(message);
                }
            } catch (SocketTimeoutException e) {
                break;
            }
        }
    } catch (IOException ex) {
    }
    return result;
}

From source file:org.dspace.app.webui.cris.validator.WSValidator.java

public void validate(Object arg0, Errors arg1) {
    User ws = (User) arg0;/*from   w w w .ja  va 2  s .  c o  m*/

    if (ws.getTypeDef().equals(User.TYPENORMAL)) {
        ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "normalAuth.username",
                "error.form.ws.username.mandatory", "Username is mandatory");
        ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "normalAuth.password",
                "error.form.ws.password.mandatory", "Password is mandatory");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "specialAuth.token", "error.form.ws.token.mandatory",
                "Token is mandatory");
        ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "specialAuth.fromIP", "error.form.ws.fromip.mandatory",
                "Single IP is mandatory");

        Long froms = null;
        Long tos = null;
        if (ws.getFromIP() != null && !ws.getFromIP().isEmpty()) {
            if (!validator.isValidInet4Address(ws.getFromIP())) {
                arg1.reject("specialAuth.fromIP", "from IP not well formed");
            } else {
                try {
                    froms = AddressUtils.ipToLong(InetAddress.getByName(ws.getFromIP()));
                } catch (UnknownHostException e) {
                    arg1.reject("specialAuth.fromIP", "Unknown host exception");
                }
            }

            if (ws.getToIP() != null && !ws.getToIP().isEmpty()) {
                if (!validator.isValidInet4Address(ws.getToIP())) {
                    arg1.reject("specialAuth.ToIP", "to IP not well formed");
                } else {
                    try {
                        tos = AddressUtils.ipToLong(InetAddress.getByName(ws.getToIP()));

                    } catch (UnknownHostException e) {
                        arg1.reject("specialAuth.toIP", "Unknown host exception");
                    }
                }
            }

            if (froms != null && tos != null) {

                if (froms >= tos) {
                    arg1.reject("specialAuth.toIP", "Range not well formed");
                }

            }
        }

    }

}