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.ebay.pulsar.collector.udf.GeoEnrichmentUtil.java

private GeoInfo _getGeoInfo(String ipAddress) {
    GeoInfo geoInfo = new GeoInfo();
    if (ipAddress == null) {
        return geoInfo;
    }//from ww w  . jav a  2  s . c om
    try {
        InetAddress inetAddress = InetAddress.getByName(ipAddress);
        CityResponse response = reader.city(inetAddress);

        Country country = response.getCountry();
        Continent continent = response.getContinent();

        City city = response.getCity();
        Postal postal = response.getPostal();
        Location location = response.getLocation();

        Subdivision subdivision = response.getMostSpecificSubdivision();
        geoInfo.setRegion(subdivision.getName());
        geoInfo.setCountryIsoCode(country.getIsoCode());
        geoInfo.setCountry(country.getName());
        geoInfo.setContinent(continent.getCode());
        geoInfo.setCity(city.getName());
        geoInfo.setPostalCode(postal.getCode());
        geoInfo.setLatitude(location.getLatitude());
        geoInfo.setLongitude(location.getLongitude());

        return geoInfo;
    } catch (Exception ex) {
        return null;
    }
}

From source file:epn.edu.ec.bibliotecadigital.cliente.Client.java

@Override
public void run() {
    try {//from   ww w  .  j  a va2s  . c om
        clientSocketBalancer = new Socket(InetAddress.getByName(serverIP), portBalancer);
        DataInputStream dataInBalancer = new DataInputStream(clientSocketBalancer.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocketBalancer.getOutputStream());
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        String ipServer = dataInBalancer.readUTF();
        int portServer = dataInBalancer.readInt();
        clientSocketBalancer.close();
        Socket clientSocket = new Socket(ipServer, portServer);
        dataOut = new DataOutputStream(clientSocket.getOutputStream());
        dataOut.writeUTF(accion);
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        InputStream in;
        DataInputStream dataIn;
        switch (accion) {
        case "bajar":

            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF((String) params[1]);
            dataIn = new DataInputStream(clientSocket.getInputStream());
            boolean encontrado = dataIn.readBoolean();
            if (!encontrado) {
                System.out.println("Libro con el cdigo: " + params[1] + " no encontrado");
                break;
            }
            String fileName = dataIn.readUTF();
            System.out.println(
                    "Descargando libro " + fileName + " con cdigo " + params[1] + " en la carpeta Donwloads");
            String home = System.getProperty("user.home");

            in = clientSocket.getInputStream();
            try {
                FileOutputStream out = new FileOutputStream(new File(home + "\\Downloads\\" + fileName));
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "subir":
            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF(((File) params[1]).getName());
            OutputStream out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                in = new FileInputStream((File) params[1]);

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "obtenerLista":
            ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Libros disponibles: \n");
            List<Libro> libros = (List<Libro>) inFromClient.readObject();
            System.out.println("\tCdigo\tNommbre\n");
            for (Libro lbr : libros) {
                System.out.println("\t" + lbr.getCodigolibro() + "\t" + lbr.getNombre());
            }
            inFromClient.close();
            break;
        case "verificar":

            break;
        }
        dataOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.sf.jabref.logic.remote.server.RemoteListenerServer.java

public RemoteListenerServer(MessageHandler messageHandler, int port) throws IOException {
    this.serverSocket = new ServerSocket(port, BACKLOG, InetAddress.getByName("localhost"));
    this.messageHandler = messageHandler;
}

From source file:examples.chargen.java

public static final void chargenUDP(String host) throws IOException {
    int packets = 50;
    byte[] data;//from  w w  w .j a v a 2s .  c o m
    InetAddress address;
    CharGenUDPClient client;

    address = InetAddress.getByName(host);
    client = new CharGenUDPClient();

    client.open();
    // If we don't receive a return packet within 5 seconds, assume
    // the packet is lost.
    client.setSoTimeout(5000);

    while (packets-- > 0) {
        client.send(address);

        try {
            data = client.receive();
        }
        // Here we catch both SocketException and InterruptedIOException,
        // because even though the JDK 1.1 docs claim that
        // InterruptedIOException is thrown on a timeout, it seems
        // SocketException is also thrown.
        catch (SocketException e) {
            // We timed out and assume the packet is lost.
            System.err.println("SocketException: Timed out and dropped packet");
            continue;
        } catch (InterruptedIOException e) {
            // We timed out and assume the packet is lost.
            System.err.println("InterruptedIOException: Timed out and dropped packet");
            continue;
        }
        System.out.write(data);
        System.out.flush();
    }

    client.close();
}

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

@BotCommand("")
public String ping(@Option(name = "?", help = "?  ?? ? IP ") String uri) {
    InetAddress addr;//from w  w  w . java  2 s . c o  m

    try {
        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());
    }
}

From source file:jsaf.protocol.tftp.TftpURLConnection.java

public void connect() throws IOException {
    host = InetAddress.getByName(url.getHost());
    if (url.getPort() == -1) {
        port = TFTP.DEFAULT_PORT;/*from  www.  jav a2  s. c om*/
    } else {
        port = url.getPort();
    }
    client.open();
    connected = true;
}

From source file:com.mirth.connect.connectors.tcp.SocketUtil.java

public static void connectSocket(Socket socket, String host, int port, int timeout)
        throws UnknownHostException, IOException {
    socket.connect(new InetSocketAddress(InetAddress.getByName(TcpUtil.getFixedHost(host)), port), timeout);
}

From source file:net.fenyo.gnetwatch.GenericTools.java

/**
 * Converts a string to an Inet4Address.
 * @param str source string.//from  www. ja  v a  2  s.  co  m
 * @return Inet4Address address representing this string.
 */
static public Inet4Address stringToInet4Address(final String str) throws UnknownHostException {
    /*
    final Matcher match = 
      Pattern.compile("([0-9]*)\\.([0-9]*)\\.([0-9]*)\\.([0-9]*)").matcher(str);
    if (match.find() == true) {
      return (Inet4Address) InetAddress.getByAddress(new byte [] {
          new Integer(match.group(1)).byteValue(), 
          new Integer(match.group(2)).byteValue(), 
          new Integer(match.group(3)).byteValue(), 
          new Integer(match.group(4)).byteValue(), 
      });
    } else return stringToInet4Address("0.0.0.0");
    */
    // shortest alternative to the previous code:
    return (Inet4Address) InetAddress.getByName(str);
}

From source file:com.l2jfree.loginserver.thread.FloodProtectedListener.java

public FloodProtectedListener(String listenIp, int port) {
    try {/*from  w w  w  . j  a  v  a 2s . co  m*/
        if (listenIp.equals("*"))
            _serverSocket = new ServerSocket(port);
        else
            _serverSocket = new ServerSocket(port, 50, InetAddress.getByName(listenIp));
    } catch (IOException e) {
        throw new RuntimeException("Error creating ServerSocket: ", e);
    }
}

From source file:examples.echo.java

public static final void echoUDP(String host) throws IOException {
    int length, count;
    byte[] data;//from  ww  w .  j ava2s .co  m
    String line;
    BufferedReader input;
    InetAddress address;
    EchoUDPClient client;

    input = new BufferedReader(new InputStreamReader(System.in));
    address = InetAddress.getByName(host);
    client = new EchoUDPClient();

    client.open();
    // If we don't receive an echo within 5 seconds, assume the packet is lost.
    client.setSoTimeout(5000);
    System.out.println("Ready to echo to " + host + ".");

    // Remember, there are no guarantees about the ordering of returned
    // UDP packets, so there is a chance the output may be jumbled.
    while ((line = input.readLine()) != null) {
        data = line.getBytes();
        client.send(data, address);
        count = 0;
        do {
            try {
                length = client.receive(data);
            }
            // Here we catch both SocketException and InterruptedIOException,
            // because even though the JDK 1.1 docs claim that
            // InterruptedIOException is thrown on a timeout, it seems
            // SocketException is also thrown.
            catch (SocketException e) {
                // We timed out and assume the packet is lost.
                System.err.println("SocketException: Timed out and dropped packet");
                break;
            } catch (InterruptedIOException e) {
                // We timed out and assume the packet is lost.
                System.err.println("InterruptedIOException: Timed out and dropped packet");
                break;
            }
            System.out.print(new String(data, 0, length));
            count += length;
        } while (count < data.length);

        System.out.println();
    }

    client.close();
}