Example usage for java.net InetAddress toString

List of usage examples for java.net InetAddress toString

Introduction

In this page you can find the example usage for java.net InetAddress toString.

Prototype

public String toString() 

Source Link

Document

Converts this IP address to a String .

Usage

From source file:org.apache.hadoop.net.TestDNS.java

/**
 * Test that the name "localhost" resolves to something.
 *
 * If this fails, your machine's network is in a mess, go edit /etc/hosts
 *//*  w  w  w .j  a va2s.c om*/
@Test
public void testLocalhostResolves() throws Exception {
    InetAddress localhost = InetAddress.getByName("localhost");
    assertNotNull("localhost is null", localhost);
    LOG.info("Localhost IPAddr is " + localhost.toString());
}

From source file:net.geertvos.theater.core.util.UUIDGen.java

private long makeNode(InetAddress addr) {
    if (nodeCache.containsKey(addr))
        return nodeCache.get(addr);

    // ideally, we'd use the MAC address, but java doesn't expose that.
    byte[] hash = hash(ByteBuffer.wrap(addr.toString().getBytes()));
    long node = 0;
    for (int i = 0; i < Math.min(6, hash.length); i++)
        node |= (0x00000000000000ff & (long) hash[i]) << (5 - i) * 8;
    assert (0xff00000000000000L & node) == 0;

    nodeCache.put(addr, node);//w  w  w  .  ja  va  2 s.  c om

    return node;

}

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

/**
 * Constructor./*w w  w.ja  va  2 s  .  c  o m*/
 * @param address target address.
 */
public IPQuerier(final InetAddress address) {
    this.address = address;
    if (Inet4Address.class.isInstance(address))
        this.URL = "http://" + address.toString().substring(1) + ":80/";
    if (Inet6Address.class.isInstance(address))
        this.URL = "http://[" + address.toString().substring(1) + "]:80/";
    parametersHaveChanged();
}

From source file:be.tutul.naheulcraft.launcher.auth.Auth.java

public void logIn() {
    new Thread() {
        private Socket ss;
        private BufferedReader in;
        private PrintWriter out;

        public void run() {
            try {
                InetAddress adresse = InetAddress.getByName("naheulcraft.be"); // Rcupre l'adresse IP
                String IP = adresse.toString().split("/")[1];
                Auth.this.logger.info("Connexion  " + IP + ":" + Variables.PORT);
                this.ss = new Socket(IP, Variables.PORT);

                this.in = new BufferedReader(new InputStreamReader(this.ss.getInputStream()));
                this.out = new PrintWriter(this.ss.getOutputStream());

                // On signale au serveur qu'on demande une authentification
                this.out.println("<start>");
                this.out.flush();
                String ok = this.in.readLine();
                if (!ok.contains("<ok>")) {
                    Auth.this.launcher.getPanel().getLogInPopup().setText("Rponse innatendu du serveur");
                    Auth.this.launcher.getPanel().getLogInPopup().setCanLogIn(true);
                    Auth.this.launcher.getPanel().showLoginPrompt();
                    return;
                }/*from   w ww.j av  a 2  s  .  c om*/

                Auth.this.logger.info("Connexion au service de login tablie");

                String key = ok.split("<ok>")[1]; // On rcure la cl
                String msg = Auth.this.launcher.getUser().getPseudo() + ":"
                        + Auth.this.launcher.getUser().getPass() + ":" + Variables.version + "<end>";
                System.err.println("A : " + msg);//TODO
                msg = crypt(msg, key); // On crypt en base 64

                // On lui envoit la requte
                Auth.this.logger.info("Vrification du login en cours...");
                System.err.println("B : " + msg);//TODO
                this.out.println(msg);
                this.out.flush();

                String login = this.in.readLine();
                login = decrypt(login, key); // On dcrypt en string
                System.err.println("C : " + login);//TODO

                // On ferme le socket
                this.in.close();
                this.out.close();
                this.ss.close();

                String ret;
                if (login != null) {
                    if (login.contains("pass")) {
                        ret = "Mauvais mot de passe";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("user")) {
                        ret = "Mauvais pseudo";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("statut")) {
                        ret = "Compte n'ont autoris";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("encodage")) {
                        ret = "Problme dans la demande de login";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.error(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("serveur")) {
                        ret = "Erreur du service de login";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.error(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("<ok>")) {
                        String id = login.split("<end>")[0].split("<ok>")[1];
                        Auth.this.launcher.getUser().setID(id);
                        Auth.this.launcher.getUser().setLogin(true);
                        Auth.this.logger.info("Login vrifier avec succs");
                        Auth.this.logger.info("ID de connexion : " + id);
                        Auth.this.lastLogin.writeUsername();
                        Auth.this.launcher.getPanel().showPanel();
                        return;
                    } else {
                        Auth.this.logger.error(login);
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.launcher.getPanel().getLogInPopup().setText("Erreur inconnue");
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    }
                }
                Auth.this.logger.error("Pas de rponse du serveur");
                Auth.this.launcher.getUser().setLogin(false);
                Auth.this.launcher.getPanel().getLogInPopup().setText("Pas de rponse");
                Auth.this.launcher.getPanel().showLoginPrompt();
            } catch (Exception e) {
                Auth.this.logger.fatal("Impossible de communiquer avec le service de login", e);
                Auth.this.launcher.getUser().setLogin(false);
                Auth.this.launcher.getPanel().getLogInPopup().setText("Problme de communication");
                Auth.this.launcher.getPanel().showLoginPrompt();
                try { // On tente quand mme de couper le socket
                    this.in.close();
                    this.out.close();
                    this.ss.close();
                } catch (Exception ingnored) {
                }
            }
        }
    }.start();
}

From source file:com.wifichat.connection.ChatConnection.java

public void connectToServer(InetAddress address, int port) {
    Log.d(TAG, "Connecting to server: " + address.toString() + " " + port);
    mChatClient = new ChatClient(address, port);
}

From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java

private void asyncSend(String urlStr, Map<String, String> paramsMap, boolean post) throws IOException {

    String p = "http://(.*):";
    Pattern pattern = Pattern.compile(p);

    Matcher matcher = pattern.matcher(urlStr);

    String host = null;//from ww w  .j  av  a 2 s.c  o m
    while (matcher.find()) {
        host = matcher.group(1);
    }

    if (!Character.isDigit(host.charAt(0))) {
        InetAddress address = InetAddress.getByName(host);

        String a = address.toString();

        a = a.substring(a.indexOf('/') + 1);

        urlStr = urlStr.replace(host, a);
    }
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    for (String key : paramsMap.keySet()) {

        BasicNameValuePair pair = new BasicNameValuePair(key, paramsMap.get(key));
        list.add(pair);
    }

    client.asyncForwardRequest(urlStr, list);

}

From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java

/**
 * Sends data to the specified url via a HTTP POST, and returns the reply
 * @param urlStr the url to connect to//from  w w w . j  a  v a2s  .c o  m
 * @param paramsMap a map of attribute=value pairs representing the data to send
 * @param post true if this was originally a POST request, false if a GET request
 * @return the response from the url
 * @throws IOException when there's some kind of communication problem
 */
private String send(String urlStr, Map<String, String> paramsMap, boolean post) throws IOException {

    String p = "http://(.*):";
    Pattern pattern = Pattern.compile(p);

    Matcher matcher = pattern.matcher(urlStr);

    String host = null;
    while (matcher.find()) {
        host = matcher.group(1);
    }

    if (!Character.isDigit(host.charAt(0))) {
        InetAddress address = InetAddress.getByName(host);

        String a = address.toString();

        a = a.substring(a.indexOf('/') + 1);

        urlStr = urlStr.replace(host, a);
    }
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    for (String key : paramsMap.keySet()) {

        BasicNameValuePair pair = new BasicNameValuePair(key, paramsMap.get(key));
        list.add(pair);
    }

    String result = client.forwardRequest(urlStr, list);
    if (post) {
        return stripOuterElement(result);
    } else {
        return result;
    }

}

From source file:com.mgmtp.perfload.perfmon.PerfMon.java

void writeHeader() {
    String hostName = PerfMonUtils.getHostName();

    StringBuilder metaBuffer = new StringBuilder(200);
    metaBuffer.append(DATE_FORMAT.format(System.currentTimeMillis()));
    metaBuffer.append(SEPARATOR);/*w  ww .  j a  v  a2  s.c  om*/
    metaBuffer.append("meta");
    metaBuffer.append(SEPARATOR);
    metaBuffer.append("perfMon ").append(PerfMonUtils.getPerfMonVersion());
    metaBuffer.append(SEPARATOR);
    metaBuffer.append(hostName);

    LOG.info("Hostname: {}", hostName);
    try {
        LOG.info("CPUs: {}", sigar.getCpuList().length);
        LOG.info("Total RAM: {} MB", sigar.getMem().getRam());
        LOG.info("Uptime: {}", Uptime.getInfo(sigar));
    } catch (SigarException ex) {
        LOG.error("Error retrieving system information from Sigar.", ex);
    }

    try {
        InetAddress[] networkIPAddresses = PerfMonUtils.getNetworkIPAddresses();
        if (networkIPAddresses.length > 0) {
            LOG.info("Local IP addresses:");
            metaBuffer.append(SEPARATOR);
            for (int i = 0; i < networkIPAddresses.length; ++i) {
                InetAddress ip = networkIPAddresses[i];
                if (i > 0) {
                    metaBuffer.append(',');
                }
                metaBuffer.append(ip);
                LOG.info(ip.toString());
            }
        }
    } catch (UnknownHostException ex) {
        LOG.error("Error retrieving IP addresses of the localhost.", ex);
    }

    try {
        LOG.info("Full list of network interfaces:");
        List<NetworkInterface> networkInterfaces = PerfMonUtils.getNetworkInterfaces();
        for (NetworkInterface ni : networkInterfaces) {
            for (Enumeration<InetAddress> en = ni.getInetAddresses(); en.hasMoreElements();) {
                LOG.info("\t\t{}", en.nextElement().toString());
            }
        }
    } catch (SocketException ex) {
        LOG.error("Error retrieving network interfaces.", ex);
    }

    outputHandler.writeln(metaBuffer.toString());
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
 *//*from   w w w.ja v a2  s  . c o  m*/
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(new Socket(host, port), clientHost.toString(), clientPort,
            true);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:org.apache.axis.utils.Admin.java

/**
 * host validation logic goes here//  w  w  w . j  ava 2s  . c  o m
 * @param msgContext
 * @throws AxisFault
 */
private void verifyHostAllowed(MessageContext msgContext) throws AxisFault {
    /** For now, though - make sure we can only admin from our own
     * IP, unless the remoteAdmin option is set.
     */
    Handler serviceHandler = msgContext.getService();
    if (serviceHandler != null && !JavaUtils.isTrueExplicitly(serviceHandler.getOption("enableRemoteAdmin"))) {

        String remoteIP = msgContext.getStrProp(Constants.MC_REMOTE_ADDR);
        if (remoteIP != null
                && !(remoteIP.equals(NetworkUtils.LOCALHOST) || remoteIP.equals(NetworkUtils.LOCALHOST_IPV6))) {

            try {
                InetAddress myAddr = InetAddress.getLocalHost();
                InetAddress remoteAddr = InetAddress.getByName(remoteIP);
                if (log.isDebugEnabled()) {
                    log.debug("Comparing remote caller " + remoteAddr + " to " + myAddr);
                }

                if (!myAddr.equals(remoteAddr)) {
                    log.error(Messages.getMessage("noAdminAccess01", remoteAddr.toString()));
                    throw new AxisFault("Server.Unauthorized", Messages.getMessage("noAdminAccess00"), null,
                            null);
                }
            } catch (UnknownHostException e) {
                throw new AxisFault("Server.UnknownHost", Messages.getMessage("unknownHost00"), null, null);
            }
        }
    }
}