Example usage for java.net InetAddress getHostAddress

List of usage examples for java.net InetAddress getHostAddress

Introduction

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

Prototype

public String getHostAddress() 

Source Link

Document

Returns the IP address string in textual presentation.

Usage

From source file:gravity.android.discovery.DiscoveryClient.java

public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) {
    ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>();

    try {/*from www . ja  va2 s  .com*/
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.setBroadcast(true);
        InetAddress IPAddress = Utils.getBroadcastAddress(mWifi);
        Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress());
        byte[] receiveData = new byte[2048];
        byte[] sendData = new byte[128];

        sendData = token.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        Log.v("DISCOVERY_CLIENT", "sent " + token);
        clientSocket.send(sendPacket);

        long t1 = System.currentTimeMillis();
        while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            try {
                clientSocket.setSoTimeout(500);
                clientSocket.receive(receivePacket);

                if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) {
                    String discovered_name, discovered_ip;
                    int discovered_port;

                    String received = new String(receivePacket.getData());

                    if (received != null) {
                        received = received.trim().substring(0, receivePacket.getLength()).trim();
                        Log.d("Recieved Msg Packet:", received);

                        //StringTokenizer st = new StringTokenizer(received, ",");

                        //Gravity Code
                        JSONObject recievedJson = new JSONObject(received);

                        try {
                            //discovered_name = st.nextToken();   
                            discovered_name = recievedJson.getString("name"); //Gravity code

                            discovered_ip = receivePacket.getAddress().getHostAddress();

                            //discovered_port = Integer.parseInt(st.nextToken());
                            discovered_port = recievedJson.getInt("port_to_share"); //Gravity code

                            Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip
                                    + ":" + discovered_port);

                            boolean add = true;
                            if (ret.size() > 0) {
                                for (DiscoveryServerInfo dsi : ret) {
                                    if (dsi != null && dsi.ip.equals(discovered_ip)) {
                                        add = false;
                                        break;
                                    }
                                }
                            }

                            if (add) {
                                ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip,
                                        discovered_port));
                            }
                        } catch (NoSuchElementException nsee) {
                            Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage());
                        }

                    }
                }

            } catch (SocketTimeoutException tex) {
                /* ignored */ }
        }

        clientSocket.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("DISCOVERY_CLIENT", ex.toString());
    }

    return ret;
}

From source file:amplify.NTPClient.java

public static void syncServerTime(String ntpServerAddress) throws IOException {
    NTPUDPClient client = new NTPUDPClient();

    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);/*from  w  w w.  j ava2  s.  c  om*/
    try {
        client.open();
        System.out.println();
        try {
            InetAddress hostAddr = InetAddress.getByName(ntpServerAddress);
            System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
            TimeInfo info = client.getTime(hostAddr);
            processResponse(info);
        } catch (IOException ioe) {
            client.close();
            throw ioe;
        }
    } catch (SocketException e) {
        client.close();
        throw e;
    }

    client.close();
}

From source file:com.apporiented.hermesftp.utils.NetUtils.java

/**
 * Checks if the passed IP address complies to a given pattern.
 * /*  w ww. ja  v  a 2s . co  m*/
 * @param ipTemplateList String list of patterns. Wild cards are allowed: 192.168.*.*, 127.0.0.1, !85.0.0.0
 * @param addr The IP address to check.
 * @return True, if the passed IP address matches at least one of the
 *         patterns.
 */
public static boolean checkIPMatch(String ipTemplateList, InetAddress addr) {
    if (isIPv6(addr)) {
        return checkIPv6Match(ipTemplateList, addr.getHostAddress());
    } else {
        return checkIPv4Match(ipTemplateList, addr.getHostAddress());
    }
}

From source file:com.DPFaragir.DPFUtils.java

public static String getIPAddress(boolean useIPv4) {
    try {//from  www  . ja  v  a2  s .  c  o m
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:com.ery.ertc.estorm.util.DNS.java

/**
 * Returns all the IPs associated with the provided interface, if any, in textual form.
 * //from  www  . ja v  a2s .  co  m
 * @param strInterface
 *            The name of the network interface or subinterface to query (eg eth0 or eth0:0) or the string "default"
 * @param returnSubinterfaces
 *            Whether to return IPs associated with subinterfaces of the given interface
 * @return A string vector of all the IPs associated with the provided interface
 * @throws UnknownHostException
 *             If an UnknownHostException is encountered in querying the default interface or the given interface can not be found
 * 
 */
public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException {
    if ("default".equals(strInterface)) {
        return new String[] { InetAddress.getLocalHost().getHostAddress() };
    }
    NetworkInterface netIf;
    try {
        netIf = NetworkInterface.getByName(strInterface);
        if (netIf == null) {
            netIf = getSubinterface(strInterface);
            if (netIf == null) {
                throw new UnknownHostException("Unknown interface " + strInterface);
            }
        }
    } catch (SocketException e) {
        LOG.warn("Unable to get IP for interface " + strInterface, e);
        return new String[] { InetAddress.getLocalHost().getHostAddress() };
    }

    // NB: Using a LinkedHashSet to preserve the order for callers
    // that depend on a particular element being 1st in the array.
    // For example, getDefaultIP always returns the first element.
    LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>();
    allAddrs.addAll(Collections.list(netIf.getInetAddresses()));
    if (!returnSubinterfaces) {
        allAddrs.removeAll(getSubinterfaceInetAddrs(netIf));
    }

    String ips[] = new String[allAddrs.size()];
    int i = 0;
    for (InetAddress addr : allAddrs) {
        ips[i++] = addr.getHostAddress();
    }
    return ips;
}

From source file:massbank.svn.SVNUtils.java

/**
 * /*from  ww w  .  j a v  a  2  s  .c  om*/
 */
public static String getLocalIPAddress() {
    String address = "";
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface network = interfaces.nextElement();
            Enumeration<InetAddress> addresses = network.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress inet = addresses.nextElement();
                if (!inet.isLoopbackAddress() && inet instanceof Inet4Address) {
                    return inet.getHostAddress();
                }
            }
        }
        address = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
    }
    return address;
}

From source file:com.vinexs.tool.NetworkManager.java

public static String getIPAddress(boolean useIPv4) {
    try {//from  w  ww  .j ava  2 s .co  m
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtilsHC4.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4) {
                            return sAddr;
                        }
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.frame.network.utils.NetworkUtil.java

public static String getLocalIpv4Address() {
    try {/*from  w  w w  . j  av  a 2  s.co m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java

public static String getRemoteHost() {
    WebRequest req = (WebRequest) RequestCycle.get().getRequest();
    HttpServletRequest httpReq = (HttpServletRequest) req.getContainerRequest();
    String remoteIp = httpReq.getRemoteHost();

    String localIp = httpReq.getLocalAddr();

    if (remoteIp.equals(localIp)) {
        try {//from   w  w w  . j  av a 2  s  .c  o  m
            InetAddress inetAddress = InetAddress.getLocalHost();
            remoteIp = inetAddress.getHostAddress();
        } catch (UnknownHostException ex) {
            LOGGER.error("Can't get local host: " + ex.getMessage());
        }
    }
    return remoteIp;
}

From source file:com.vmware.identity.idm.CommonUtil.java

private static String findInetAddress(Predicate<InetAddress> match) throws SocketException {
    String ipAddress = null;//from   w  ww . ja v a 2s . co m
    Enumeration<NetworkInterface> it = NetworkInterface.getNetworkInterfaces();

    while ((ipAddress == null) && it.hasMoreElements()) {
        NetworkInterface iface = it.nextElement();
        if ((!iface.isLoopback()) && (iface.isUp())) {
            Enumeration<InetAddress> it2 = iface.getInetAddresses();

            while (it2.hasMoreElements()) {
                InetAddress addr = it2.nextElement();
                if (match.matches(addr)) {
                    ipAddress = addr.getHostAddress();
                    break;
                }
            }
        }
    }

    return ipAddress;
}