Example usage for java.net InetAddress isLoopbackAddress

List of usage examples for java.net InetAddress isLoopbackAddress

Introduction

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

Prototype

public boolean isLoopbackAddress() 

Source Link

Document

Utility routine to check if the InetAddress is a loopback address.

Usage

From source file:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java

/**
 * Checks the IP from the incoming request Only connections from localhost
 * are allowed/*  w  w  w  . j  av  a 2s  . c  o m*/
 *
 * @param request The incoming request
 * @throws AccessDeniedException if the remote IP is not localhost
 */
private void checkRemoteIP(HttpServletRequest request) throws AccessDeniedException, UnknownHostException {
    InetAddress addr = InetAddress.getByName(request.getRemoteAddr());
    if (!addr.isLoopbackAddress()) {
        throw new AccessDeniedException("Only connections from localhost are allowed");
    }
}

From source file:org.psit.transwatcher.TransWatcher.java

private String getBroadcastIP() {
    String myIP = null;/*from ww w  .  j  a v  a 2s .  c  om*/

    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && myIP == null) {
            NetworkInterface current = interfaces.nextElement();
            notifyMessage(current.toString());
            notifyMessage("Name: " + current.getName());
            if (!current.isUp() || current.isLoopback() || current.isVirtual()
                    || !current.getName().startsWith("wl"))
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr.isLoopbackAddress())
                    continue;
                if (current_addr instanceof Inet4Address) {
                    myIP = current_addr.getHostAddress();
                    break;
                }
            }
        }
    } catch (Exception exc) {
        notifyMessage("Error determining network interfaces:\n");
    }

    if (myIP != null) {
        // broadcast for IPv4
        StringTokenizer st = new StringTokenizer(myIP, ".");
        StringBuffer broadcastIP = new StringBuffer();
        // hate that archaic string puzzle
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append(st.nextElement());
        broadcastIP.append(".");
        broadcastIP.append("255");
        return broadcastIP.toString();
    }

    return null;
}

From source file:org.sonar.server.platform.ServerIdGenerator.java

boolean isFixed(InetAddress address) {
    // Loopback addresses are in the range 127/8.
    // Link local addresses are in the range 169.254/16 (IPv4) or fe80::/10 (IPv6). They are "autoconfiguration" addresses.
    // They can assigned pseudorandomly, so they don't guarantee to be the same between two server startups.
    return acceptPrivateAddress || (!address.isLoopbackAddress() && !address.isLinkLocalAddress());
}

From source file:com.vangent.hieos.logbrowser.servlets.AuthenticationServlet.java

/**
 * //from   w  w w.  j  ava  2 s  .c  om
 *  Entry point of the servlet
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("text/xml");
    HttpSession session = req.getSession(true);
    String passwordInput = req.getParameter("password");
    String newPassword = req.getParameter("chgPassword");
    String getIsAdmin = req.getParameter("isAdmin");
    String logout = req.getParameter("logout");
    String ipFrom = req.getRemoteAddr();
    String company = null;
    try {
        InetAddress address = InetAddress.getByName(ipFrom);
        if (address instanceof Inet6Address) {
            if (address.isLoopbackAddress()) {
                ipFrom = "127.0.0.1";
            } else {
                ipFrom = "null";
            }
        }
    } catch (UnknownHostException e) {
    }

    if (ipFrom != null && !ipFrom.equals("null")) {
        Log log = new Log();
        try {
            PreparedStatement selectCompanyName = null;
            Connection con = log.getConnection();
            selectCompanyName = con.prepareStatement("SELECT company_name,email FROM ip where ip = ? ; ");
            selectCompanyName.setString(1, ipFrom);
            ResultSet result = selectCompanyName.executeQuery();
            if (result.next()) {
                company = result.getString(1).replaceAll("'", "&quot;");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (LoggerException e) {
            e.printStackTrace();
        } finally {
            try {
                log.closeConnection();
            } catch (LoggerException ex) {
                Logger.getLogger(AuthenticationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    String pageNumber = (String) session.getAttribute("page");
    String numberResultsByPage = (String) session.getAttribute("numberResultsByPage");
    session.setAttribute("isAdmin", true); // BHT (HACK).

    // DISABLED (BHT)
    // readFile();
    if (passwordInput != null) {
        try {
            if (passwordRead.equals(passwordInput)) {
                session.setAttribute("isAdmin", true);
                if (newPassword != null) {
                    FileWriter fstream;
                    try {
                        fstream = new FileWriter(passwordFile);
                        BufferedWriter out = new BufferedWriter(fstream);
                        out.write(newPassword);
                        out.close();
                        res.getWriter()
                                .write("<response isChanged='true' isAuthenticated='true' page ='" + pageNumber
                                        + "' numberResultByPage='" + numberResultsByPage + "'></response>");

                    } catch (IOException e) {
                        try {
                            res.getWriter().write("<response isChanged='false' page ='" + pageNumber
                                    + "' numberResultByPage='" + numberResultsByPage + "' ip='" + ipFrom + "' +"
                                    + " company='" + company + "' > " + e.getMessage() + "</response>");
                        } catch (IOException e1) {
                        }
                    }

                } else {
                    res.getWriter().write("<response isAuthenticated='true' page ='" + pageNumber
                            + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                }
            } else {
                res.getWriter().write("<response isAuthenticated='false' ip='" + ipFrom + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (Exception e) {
        }
    } else if (getIsAdmin != null && getIsAdmin.equals("get")) {
        try {
            Boolean isAuthenticated = (Boolean) session.getAttribute("isAdmin");
            String sysType = (String) session.getAttribute("systemType");

            if (sysType == null) {
                sysType = "new";
            }

            if (isAuthenticated != null && isAuthenticated.booleanValue()) {
                res.getWriter().write("<response isAuthenticated='true' systemType='" + sysType + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                /*} else if (authorizedIPs.contains(ipFrom)) {
                res.getWriter().write(
                "<response isAuthenticated='true'" + " page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                session.setAttribute("isAdmin", true);
                }*/
            } else {
                res.getWriter()
                        .write("<response isAuthenticated='false' ip='" + ipFrom + "' systemType ='" + sysType
                                + "' company    ='" + company + "' page       ='" + pageNumber
                                + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (IOException e) {
        }
    } else if (logout != null && logout.equals("yes")) {
        session.invalidate();
        try {
            res.getWriter().write("<response/>");
        } catch (IOException e) {
        }
    }
}

From source file:com.taobao.adfs.util.Utilities.java

public static List<InetAddress> getInetAddressList(List<InetAddress> addressList, String type)
        throws IOException {
    type = type.toLowerCase();// ww  w .  j  ava  2s.c  o m
    List<InetAddress> newAddressList = new ArrayList<InetAddress>();
    for (InetAddress address : addressList) {
        if (address.isLinkLocalAddress()) {
            if (type.equals("linklocal"))
                newAddressList.add(address);
        } else if (address.isLoopbackAddress()) {
            if (type.equals("loopback"))
                newAddressList.add(address);
        } else if (address.isSiteLocalAddress()) {
            if (type.equals("lan"))
                newAddressList.add(address);
        } else {
            if (type.equals("wan"))
                newAddressList.add(address);
        }
    }
    Collections.sort(newAddressList, inetAddressComparator);
    return newAddressList;
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

/**
 * Constructs a new instance of this class.
 *//*w  w  w.j  a  va2  s  .  c  o m*/
private SsdpHandler() {
    LOG.info("Instantiating SsdpHandler");

    try {
        // Use first IPv4 address that isn't loopback, any, or link local as the server address
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && serverAddress == null) {
            NetworkInterface i = interfaces.nextElement();
            Enumeration<InetAddress> addresses = i.getInetAddresses();
            while (addresses.hasMoreElements() && serverAddress == null) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    if (!address.isAnyLocalAddress() && !address.isLinkLocalAddress()
                            && !address.isLoopbackAddress() && !address.isMulticastAddress()) {
                        serverAddress = address;
                    }
                }
            }
        }

        if (serverAddress == null) {
            LOG.warn("Server address unknown");
        }

        svc = SsdpService.forAllMulticastAvailableNetworkInterfaces(this);
        svc.listen();

        // setup Multicast for Notify messages
        notifySocket = new MulticastSocket();
        notifySocket.setTimeToLive(TTL);
        notifyTimer = new Timer("UPnP Notify Timer", true);
        notifyTimer.scheduleAtFixedRate(new NotifySender(), 5000, MAX_AGE * 1000 / 2);
    } catch (Exception e) {
        LOG.error("SsdpHandler in unknown state due to exception in constructor.", e);
    }
}

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

protected ServerSocket createSocket(URI uri) throws IOException {
    String host = uri.getHost();/* w  ww .java  2 s.com*/
    int backlog = connector.getBacklog();
    if (host == null || host.length() == 0) {
        host = "localhost";
    }
    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress()
            || host.trim().equals("localhost")) {
        return new ServerSocket(uri.getPort(), backlog);
    } else {
        return new ServerSocket(uri.getPort(), backlog, inetAddress);
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java

/**
 * Checks if the address is local.//from   w w  w  . ja v  a2s. c  o  m
 */
private boolean isLocalIpAddress(InetAddress addr) {
    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
        return true;
    try {
        return NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
        return false;
    }
}

From source file:com.example.android.toyvpn.ToyVpnService.java

public String getLocalIpAddress() {
    String ipv4;//from   w  w  w  . jav a2s  . c  o m
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                // System.out.println("ip1--:" + inetAddress);
                // System.out.println("ip2--:" + inetAddress.getHostAddress());

                // for getting IPV4 format
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {

                    String ip = inetAddress.getHostAddress().toString();
                    //  System.out.println("ip---::" + ip);
                    // return inetAddress.getHostAddress().toString();
                    return ipv4;
                }
            }
        }
    } catch (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

From source file:com.cellbots.httpserver.HttpCommandServer.java

public String getLocalIpAddress() {
    try {/*w  ww .  j  a  v  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()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("", ex.toString());
    }
    return null;
}