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.bitsofproof.supernode.core.FixedAddressDiscovery.java

@Override
public List<InetSocketAddress> discover() {
    List<InetSocketAddress> al = new ArrayList<InetSocketAddress>();
    try {/*  ww w . j av a  2 s. co m*/
        String[] split = connectTo.split(":");
        if (split.length == 2) {
            al.add(new InetSocketAddress(InetAddress.getByName(split[0]), Integer.valueOf(split[1])));
        } else {
            al.add(new InetSocketAddress(InetAddress.getByName(split[0]), chain.getPort()));
        }
    } catch (Exception e) {
        log.error("can not connect to " + connectTo, e);
    }
    return al;
}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;//ww w  .j a v a2 s.c om
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:SocketAddressEncoder.java

public static InetSocketAddress decode(String str) throws UnknownHostException {
    StringTokenizer st = new StringTokenizer(str, ",");
    if (st.countTokens() != 6) {
        throw new Exception("Illegal amount of tokens");
    }/*from   w w w.jav  a 2  s.  c  om*/

    StringBuffer sb = new StringBuffer();
    try {
        sb.append(convertAndValidateNumber(st.nextToken()));
        sb.append('.');
        sb.append(convertAndValidateNumber(st.nextToken()));
        sb.append('.');
        sb.append(convertAndValidateNumber(st.nextToken()));
        sb.append('.');
        sb.append(convertAndValidateNumber(st.nextToken()));
    } catch (IllegalArgumentException e) {
        throw new Exception(e.getMessage());
    }

    InetAddress dataAddr = InetAddress.getByName(sb.toString());

    // get data server port
    int dataPort = 0;
    try {
        int hi = convertAndValidateNumber(st.nextToken());
        int lo = convertAndValidateNumber(st.nextToken());
        dataPort = (hi << 8) | lo;
    } catch (IllegalArgumentException ex) {
        throw new Exception("Invalid data port: " + str);
    }

    return new InetSocketAddress(dataAddr, dataPort);
}

From source file:be.error.rpi.adc.ObjectStatusUdpSender.java

public ObjectStatusUdpSender(final String host, int port) throws Exception {
    this.host = host;
    this.port = port;
    this.IPAddress = InetAddress.getByName(host);
    this.clientSocket = new DatagramSocket();
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitDomainHandler.java

/**
 * {@inheritDoc}/*www.  ja  va 2 s . co  m*/
 */
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
    final String domain = cookie.getDomain();
    if (domain == null) {
        return false;
    }
    if (domain.indexOf('.') == -1
            && !HtmlUnitBrowserCompatCookieSpec.LOCAL_FILESYSTEM_DOMAIN.equalsIgnoreCase(domain)) {
        try {
            InetAddress.getByName(domain);
        } catch (final UnknownHostException e) {
            return false;
        }
    }

    return super.match(cookie, origin);
}

From source file:easy.api.service.ComponentSocket.java

public String send() throws UnknownHostException, SocketException, IOException {
    String result = "";
    // create socket to IP
    final InetAddress inetAddress = InetAddress.getByName(this.ipAddress);
    byte[] base64String = Base64.decodeBase64(this.magicPacketBase64.getBytes());
    //byte[] base64String = Base64.decodeBase64(this.magicPacketBase64);
    DatagramPacket datagramPacket = new DatagramPacket(base64String, base64String.length, inetAddress,
            this.udpPort);
    try (DatagramSocket datagramSocket = new DatagramSocket()) {
        datagramSocket.send(datagramPacket);
        result += this.magicPacketBase64 + " send successfull!!\n";
    } catch (Exception e) {
        result += e.getMessage();// w w  w . j a va  2  s  .  c om
    }
    return result;
}

From source file:com.nesscomputing.jmx.starter.guice.JmxExporterConfigProvider.java

@Inject
public JmxExporterConfigProvider(final JmxStarterConfig jmxStarterConfig) throws IOException {
    this.configuredPort = jmxStarterConfig.getBindPort();
    this.configuredHost = jmxStarterConfig.getBindAddress() == null ? null
            : InetAddress.getByName(jmxStarterConfig.getBindAddress());
}

From source file:de.ailis.oneinstance.OneInstanceServer.java

/**
 * Constructor./*w ww  . j a v a 2  s . co  m*/
 * 
 * @param appId
 *            The application name.
 * @param port
 *            The application port.
 * @throws PortAlreadyInUseException
 *             When port is already in use.
 */
OneInstanceServer(final String appId, final int port) throws PortAlreadyInUseException {
    this.appId = appId;
    this.port = port;

    try {
        this.socket = new ServerSocket(this.port, 50, InetAddress.getByName(null));
        this.socket.setSoTimeout(250);
    } catch (final IOException e) {
        throw new PortAlreadyInUseException();
    }
}

From source file:jp.co.opentone.bsol.framework.core.elasticsearch.ElasticSearchTest.java

@BeforeClass
public static void classSetup() throws Exception {
    // REST API???9200???Java API????9300
    InetAddress address = InetAddress.getByName("192.168.99.100");
    client = TransportClient.builder().build()
            .addTransportAddress(new InetSocketTransportAddress(address, 9300));
}

From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java

public void run() {
    Socket socket;//from   w w w. ja va 2 s .c  o m
    BufferedReader input;
    BufferedWriter output;

    kuc_log.i("Connecting to server at " + server_ip);

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        kuc_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        kuc_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        kuc_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        kuc_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        kuc_log.i("Requesting a key update.");
        output.write("302 request key update");
        output.newLine();
        output.flush();

        kuc_log.i("Awaiting response from server.");
        String update = input.readLine();
        switch (update) {
        case "303 update":
            kuc_log.i("Server accepted update request, sending public key.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "304 no update":
            kuc_log.i("Server rejected update request, closing connection.");
            input.close();
            output.close();
            break;
        case "305 update unavailable":
            kuc_log.i("Server cannot update at this time, try again later.");
            input.close();
            output.close();
            break;
        default:
            kuc_log.i("Server sent back invalid response");
            input.close();
            output.close();
            break;
        }
    } catch (IOException e) {
        kuc_log.e("Error in key update request!");
        e.printStackTrace();
    }
}