Search in sources :

Example 81 with Inet6Address

use of java.net.Inet6Address in project BiglyBT by BiglySoftware.

the class DNSUtilsImpl method getAllIPV6ByName.

public List<Inet6Address> getAllIPV6ByName(String host) throws UnknownHostException {
    List<Inet6Address> result = new ArrayList<>();
    try {
        DirContext context = getInitialDirContext().ctx;
        Attributes attrs = context.getAttributes(host, new String[] { "AAAA" });
        if (attrs != null) {
            Attribute attr = attrs.get("aaaa");
            if (attr != null) {
                NamingEnumeration values = attr.getAll();
                while (values.hasMore()) {
                    Object value = values.next();
                    if (value instanceof String) {
                        try {
                            result.add((Inet6Address) InetAddress.getByName((String) value));
                        } catch (Throwable e) {
                        }
                    }
                }
            }
        }
    } catch (Throwable e) {
    }
    if (result.size() > 0) {
        return (result);
    }
    throw (new UnknownHostException(host));
}
Also used : UnknownHostException(java.net.UnknownHostException) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) Inet6Address(java.net.Inet6Address) NamingEnumeration(javax.naming.NamingEnumeration) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 82 with Inet6Address

use of java.net.Inet6Address in project stdlib by petergeneric.

the class ServiceManagerHostnameRestServiceImpl method allocateHostname.

@Override
public HostnameResponseDTO allocateHostname(final HostnameRequestDTO request) {
    // Validate the IP address
    final InetAddress ip;
    try {
        ip = InetAddress.getByName(request.ip);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid/malformed IP address: " + request.ip);
    }
    // Optionally allocate a hostname
    final String hostname;
    if (request.hostname != null)
        hostname = request.hostname;
    else
        hostname = generateHostname(request.prefix);
    // Generate an SSL cert
    final LetsEncryptCertificateEntity cert = letsEncrypt.issue(hostname);
    // Set up the hostname
    if (ip instanceof Inet6Address)
        dns.createDNSRecord(hostname, RecordType.AAAA, request.ip);
    else
        dns.createDNSRecord(hostname, RecordType.A, request.ip);
    return serialise(cert);
}
Also used : LetsEncryptCertificateEntity(com.peterphi.servicemanager.service.db.entity.LetsEncryptCertificateEntity) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress)

Example 83 with Inet6Address

use of java.net.Inet6Address in project scalecube by scalecube.

the class Addressing method getNetworkInterfaceIpAddress.

/**
 * @return {@link InetAddress} by network interface name and a flag indicating whether returned IP address will be
 *         IPv4 or IPv6.
 */
private static InetAddress getNetworkInterfaceIpAddress(String listenInterface, boolean preferIPv6) {
    try {
        NetworkInterface ni = NetworkInterface.getByName(listenInterface);
        if (ni == null) {
            throw new IllegalArgumentException("Configured network interface: " + listenInterface + " could not be found");
        }
        if (!ni.isUp()) {
            throw new IllegalArgumentException("Configured network interface: " + listenInterface + " is not active");
        }
        Enumeration<InetAddress> addrs = ni.getInetAddresses();
        if (!addrs.hasMoreElements()) {
            throw new IllegalArgumentException("Configured network interface: " + listenInterface + " was found, but had no addresses");
        }
        // try to return the first address of the preferred type, otherwise return the first address
        InetAddress result = null;
        while (addrs.hasMoreElements()) {
            InetAddress addr = addrs.nextElement();
            if (preferIPv6 && addr instanceof Inet6Address) {
                return addr;
            }
            if (!preferIPv6 && addr instanceof Inet4Address) {
                return addr;
            }
            if (result == null) {
                result = addr;
            }
        }
        return result;
    } catch (SocketException e) {
        throw new IllegalArgumentException("Configured network interface: " + listenInterface + " caused an exception", e);
    }
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress)

Example 84 with Inet6Address

use of java.net.Inet6Address in project java-docs-samples by GoogleCloudPlatform.

the class CloudSqlServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL " + "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, " + "PRIMARY KEY (visit_id) )";
    final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
    final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC " + "LIMIT 10";
    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        // ignore the request for favicon.ico
        return;
    }
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");
    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }
    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();
        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("timestamp");
                out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n");
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}
Also used : ServletException(javax.servlet.ServletException) Inet4Address(java.net.Inet4Address) SQLException(java.sql.SQLException) Stopwatch(com.google.common.base.Stopwatch) ResultSet(java.sql.ResultSet) Inet6Address(java.net.Inet6Address) PreparedStatement(java.sql.PreparedStatement) InetAddress(java.net.InetAddress) Timestamp(java.sql.Timestamp) Date(java.util.Date) PrintWriter(java.io.PrintWriter)

Example 85 with Inet6Address

use of java.net.Inet6Address in project java-docs-samples by GoogleCloudPlatform.

the class DiskServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }
    Path tmpFile = Paths.get("/tmp/seen.txt");
    Files.write(tmpFile, (userIp + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    StringBuffer sb = new StringBuffer();
    List<String> strings = Files.readAllLines(tmpFile, StandardCharsets.US_ASCII);
    for (String s : strings) {
        sb.append(s + "\n");
    }
    String instanceId = System.getenv().containsKey("GAE_INSTANCE") ? System.getenv("GAE_INSTANCE") : "1";
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");
    out.print("Instance: " + instanceId + "\nSeen:\n" + sb.toString());
}
Also used : Path(java.nio.file.Path) Inet4Address(java.net.Inet4Address) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress) PrintWriter(java.io.PrintWriter)

Aggregations

Inet6Address (java.net.Inet6Address)286 InetAddress (java.net.InetAddress)196 Inet4Address (java.net.Inet4Address)110 NetworkInterface (java.net.NetworkInterface)54 UnknownHostException (java.net.UnknownHostException)51 SocketException (java.net.SocketException)32 InetSocketAddress (java.net.InetSocketAddress)31 IOException (java.io.IOException)29 LinkAddress (android.net.LinkAddress)28 Test (org.junit.Test)26 RouteInfo (android.net.RouteInfo)21 IpPrefix (android.net.IpPrefix)19 ArrayList (java.util.ArrayList)19 LinkProperties (android.net.LinkProperties)15 ByteBuffer (java.nio.ByteBuffer)9 InterfaceAddress (java.net.InterfaceAddress)7 StringJoiner (java.util.StringJoiner)7 PrintWriter (java.io.PrintWriter)6 HashMap (java.util.HashMap)6 Test (org.junit.jupiter.api.Test)6