Search in sources :

Example 61 with Inet6Address

use of java.net.Inet6Address in project graal by oracle.

the class JavavmExportJvm method NET_InetAddressToSockaddr.

/* Do not re-wrap comments: @formatter:off */
// 780 /* In the case of an IPv4 Inetaddress this method will return an
// 781 * IPv4 mapped address where IPv6 is available and v4MappedAddress is TRUE.
// 782 * Otherwise it will return a sockaddr_in structure for an IPv4 InetAddress.
// 783 */
// 784 JNIEXPORT int JNICALL
// 785 NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr *him,
// 786 int *len, jboolean v4MappedAddress) {
static int NET_InetAddressToSockaddr(InetAddress iaObj, int port, Socket.sockaddr him, CIntPointer len, boolean v4MappedAddress) throws SocketException {
    // 787 jint family;
    int family;
    // 788 family = getInetAddress_family(env, iaObj);
    family = JavaNetNetUtil.getInetAddress_family(iaObj);
    // 791 if (ipv6_available() && !(family == IPv4 && v4MappedAddress == JNI_FALSE)) {
    if (JavaNetNetUtil.ipv6_available() && (!((family == Target_java_net_InetAddress.IPv4) && (v4MappedAddress == Util_jni.JNI_FALSE())))) {
        // 792 struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
        NetinetIn.sockaddr_in6 him6 = (NetinetIn.sockaddr_in6) him;
        // 793 jbyte caddr[16];
        CCharPointer caddr = StackValue.get(16, SizeOf.get(CCharPointer.class));
        // 794 jint address;
        int address;
        // 797 if (family == IPv4) { /* will convert to IPv4-mapped address */
        if (family == Target_java_net_InetAddress.IPv4) {
            // 798 memset((char *) caddr, 0, 16);
            LibC.memset(caddr, WordFactory.zero(), WordFactory.unsigned(16));
            // 799 address = getInetAddress_addr(env, iaObj);
            address = getInetAddress_addr(iaObj);
            // 800 if (address == INADDR_ANY) {
            if (address == NetinetIn.INADDR_ANY()) {
            /* we would always prefer IPv6 wildcard address
                     * 802 caddr[10] = 0xff;
                     * 803 caddr[11] = 0xff;
                     */
            } else {
                // 805 caddr[10] = 0xff;
                caddr.write(10, (byte) 0xff);
                // 806 caddr[11] = 0xff;
                caddr.write(11, (byte) 0xff);
                // 807 caddr[12] = ((address >> 24) & 0xff);
                caddr.write(12, (byte) ((address >> 24) & 0xff));
                // 808 caddr[13] = ((address >> 16) & 0xff);
                caddr.write(13, (byte) ((address >> 16) & 0xff));
                // 809 caddr[14] = ((address >> 8) & 0xff);
                caddr.write(14, (byte) ((address >> 8) & 0xff));
                // 810 caddr[15] = (address & 0xff);
                caddr.write(15, (byte) (address & 0xff));
            }
        } else {
            // 813 getInet6Address_ipaddress(env, iaObj, (char *)caddr);
            JavaNetNetUtil.getInet6Address_ipAddress((Inet6Address) iaObj, caddr);
        }
        // 815 memset((char *)him6, 0, sizeof(struct sockaddr_in6));
        LibC.memset(him6, WordFactory.zero(), SizeOf.unsigned(NetinetIn.sockaddr_in6.class));
        // 816 him6->sin6_port = htons(port);
        him6.set_sin6_port(NetinetIn.htons(port));
        // 817 memcpy((void *)&(him6->sin6_addr), caddr, sizeof(struct in6_addr) );
        LibC.memcpy(him6.sin6_addr(), caddr, SizeOf.unsigned(NetinetIn.in6_addr.class));
        // 818 him6->sin6_family = AF_INET6;
        him6.set_sin6_family(Socket.AF_INET6());
        // 819 *len = sizeof(struct sockaddr_in6) ;
        len.write(SizeOf.get(NetinetIn.sockaddr_in6.class));
        // 821 #if defined(_ALLBSD_SOURCE) && defined(_AF_INET6)
        if (IsDefined._ALLBSD_SOURCE() && IsDefined.socket_AF_INET6()) {
        // 822 // XXXBSD: should we do something with scope id here ? see below linux comment
        // 823 /* MMM: Come back to this! */
        }
        // 838 #ifdef __linux__
        if (IsDefined.__linux__()) {
            // 839 if (IN6_IS_ADDR_LINKLOCAL(&(him6->sin6_addr))) {
            if (JavaNetNetUtilMD.IN6_IS_ADDR_LINKLOCAL(him6.sin6_addr())) {
                // 840 int cached_scope_id = 0, scope_id = 0;
                int cached_scope_id = 0;
                int scope_id = 0;
                /* I am assuming that the field "Inet6Address.cached_scope_id" always exists. */
                final boolean ia6_cachedscopeidID = true;
                // 842 if (ia6_cachedscopeidID) {
                if (ia6_cachedscopeidID) {
                    // 843     cached_scope_id = (int)(*env)->GetIntField(env, iaObj, ia6_cachedscopeidID);
                    cached_scope_id = Util_java_net_Inet6Address.from_Inet6Address((Inet6Address) iaObj).cached_scope_id;
                    // 847 if (!cached_scope_id) {
                    if (!CTypeConversion.toBoolean(cached_scope_id)) {
                        /* I am assuming that the field "Inet6Address.scope_id" exists. */
                        final boolean ia6_scopeidID = true;
                        // 848 if (ia6_scopeidID) {
                        if (ia6_scopeidID) {
                            // 849     scope_id = getInet6Address_scopeid(env, iaObj);
                            scope_id = JavaNetNetUtil.getInet6Address_scopeid((Inet6Address) iaObj);
                        }
                        // 851 if (scope_id != 0) {
                        if (scope_id != 0) {
                            // 855 if (kernelIsV24() && needsLoopbackRoute (&him6->sin6_addr)) {
                            if (JavaNetNetUtilMD.kernelIsV24() && JavaNetNetUtilMD.needsLoopbackRoute(him6.sin6_addr())) {
                                // 856 cached_scope_id = lo_scope_id;
                                cached_scope_id = lo_scope_id;
                                // 857 (*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);
                                Util_java_net_Inet6Address.from_Inet6Address((Inet6Address) iaObj).cached_scope_id = cached_scope_id;
                            }
                        } else {
                            // 864 if (kernelIsV24()) {
                            if (JavaNetNetUtilMD.kernelIsV24()) {
                                // 865 cached_scope_id = getDefaultIPv6Interface( &(him6->sin6_addr) );
                                cached_scope_id = JavaNetNetUtilMD.getDefaultIPv6Interface(him6.sin6_addr());
                            } else {
                                // 867 cached_scope_id = getLocalScopeID( (char *)&(him6->sin6_addr) );
                                cached_scope_id = JavaNetNetUtilMD.getLocalScopeID(him6.sin6_addr());
                                // 868 if (cached_scope_id == 0) {
                                if (cached_scope_id == 0) {
                                    // 869 cached_scope_id = getDefaultIPv6Interface( &(him6->sin6_addr) );
                                    cached_scope_id = getDefaultIPv6Interface(him6.sin6_addr());
                                }
                            }
                            // 872 (*env)->SetIntField(env, iaObj, ia6_cachedscopeidID, cached_scope_id);
                            Util_java_net_Inet6Address.from_Inet6Address((Inet6Address) iaObj).cached_scope_id = cached_scope_id;
                        }
                    }
                }
                // 877 /*
                // 878  * If we have a scope_id use the extended form
                // 879  * of sockaddr_in6.
                // 880  */
                // 882 struct sockaddr_in6 *him6 =
                // 883         (struct sockaddr_in6 *)him;
                NetinetIn.sockaddr_in6 him6_l882 = (NetinetIn.sockaddr_in6) him;
                // 884 him6->sin6_scope_id = cached_scope_id != 0 ?
                // 885 cached_scope_id : scope_id;
                him6_l882.set_sin6_scope_id((cached_scope_id != 0) ? cached_scope_id : scope_id);
                // 886 *len = sizeof(struct sockaddr_in6);
                len.write(SizeOf.get(NetinetIn.sockaddr_in6.class));
            }
        // 888 #else
        } else {
            // 891 if (family != IPv4) {
            if (family != Target_java_net_InetAddress.IPv4) {
                /* I am assuming that the field "Inet6Address.scopeid" exists. */
                final boolean ia6_scopeidID = true;
                // 892 if (ia6_scopeidID) {
                if (ia6_scopeidID) {
                    // 893 him6->sin6_scope_id = getInet6Address_scopeid(env, iaObj);
                    him6.set_sin6_scope_id(JavaNetNetUtil.getInet6Address_scopeid((Inet6Address) iaObj));
                }
            }
        }
    // 896 #endif /* __linux__ */
    } else // 898 #endif /* AF_INET6 */
    {
        // 900 struct sockaddr_in *him4 = (struct sockaddr_in*)him;
        NetinetIn.sockaddr_in him4 = (NetinetIn.sockaddr_in) him;
        // 901 jint address;
        int address;
        // 902 if (family == IPv6) {
        if (family == Target_java_net_InetAddress.IPv6) {
            // 903 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
            throw new SocketException("Protocol family unavailable");
        // 904 return -1;
        }
        // 906 memset((char *) him4, 0, sizeof(struct sockaddr_in));
        LibC.memset(him4, WordFactory.zero(), SizeOf.unsigned(NetinetIn.sockaddr_in.class));
        // 907 address = getInetAddress_addr(env, iaObj);
        address = getInetAddress_addr(iaObj);
        // 908 him4->sin_port = htons((short) port);
        him4.set_sin_port(NetinetIn.htons((short) port));
        // 909 him4->sin_addr.s_addr = (uint32_t) htonl(address);
        him4.sin_addr().set_s_addr(NetinetIn.htonl(address));
        // 910 him4->sin_family = AF_INET;
        him4.set_sin_family(Socket.AF_INET());
        // 911 *len = sizeof(struct sockaddr_in);
        len.write(SizeOf.get(NetinetIn.sockaddr_in.class));
    }
    // 913 return 0;
    return 0;
}
Also used : SocketException(java.net.SocketException) Inet6Address(java.net.Inet6Address) NetinetIn(com.oracle.svm.core.posix.headers.NetinetIn) CCharPointer(org.graalvm.nativeimage.c.type.CCharPointer)

Example 62 with Inet6Address

use of java.net.Inet6Address in project graal by oracle.

the class Util_jni method lookupAllHostAddr.

/* @formatter:on */
// Do not re-wrap long lines and comments: @formatter:off
@Substitute
@SuppressWarnings({ "static-method" })
public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException, SocketException, InterruptedException {
    CCharPointer hostname;
    InetAddress[] ret = null;
    int retLen = 0;
    int error = 0;
    Netdb.addrinfo hints = StackValue.get(SizeOf.get(Netdb.addrinfo.class));
    Netdb.addrinfo res = WordFactory.nullPointer();
    Netdb.addrinfoPointer resPtr = StackValue.get(SizeOf.get(Netdb.addrinfoPointer.class));
    Netdb.addrinfo resNew = WordFactory.nullPointer();
    if (host == null) {
        throw new NullPointerException("host is null");
    }
    try (CCharPointerHolder hostPin = CTypeConversion.toCString(host)) {
        // "hostname" is pinned through the end of the method.
        hostname = hostPin.get();
        // #ifdef MACOSX
        if (IsDefined.MACOSX()) {
            /*
                 * If we're looking up the local machine, attempt to get the address from
                 * getifaddrs. This ensures we get an IPv6 address for the local machine.
                 */
            ret = Util_java_net_Inet6AddressImpl.lookupIfLocalhost(hostname, true);
            if (ret != null) {
                return ret;
            }
        }
        // #endif MACOSX
        /* Try once, with our static buffer. */
        LibC.memset(hints, WordFactory.signed(0), SizeOf.unsigned(Netdb.addrinfo.class));
        hints.set_ai_flags(Netdb.AI_CANONNAME());
        hints.set_ai_family(Socket.AF_UNSPEC());
        // #endif
        try {
            // res needs cleanup at "cleanupAndReturn".
            error = Netdb.getaddrinfo(hostname, WordFactory.nullPointer(), hints, resPtr);
            if (error != 0) {
                throw new UnknownHostException(host);
            } else {
                res = resPtr.read();
                int i = 0;
                int inetCount = 0;
                int inet6Count = 0;
                int inetIndex;
                int inet6Index;
                Netdb.addrinfo itr;
                Netdb.addrinfo last = WordFactory.nullPointer();
                Netdb.addrinfo iterator = res;
                while (iterator.isNonNull()) {
                    boolean skip = false;
                    itr = resNew;
                    while (itr.isNonNull()) {
                        if ((iterator.ai_family() == itr.ai_family()) && (iterator.ai_addrlen() == itr.ai_addrlen())) {
                            if (itr.ai_family() == Socket.AF_INET()) {
                                NetinetIn.sockaddr_in addr1;
                                NetinetIn.sockaddr_in addr2;
                                addr1 = (NetinetIn.sockaddr_in) iterator.ai_addr();
                                addr2 = (NetinetIn.sockaddr_in) itr.ai_addr();
                                if (addr1.sin_addr().s_addr() == addr2.sin_addr().s_addr()) {
                                    skip = true;
                                    break;
                                }
                            } else {
                                NetinetIn.sockaddr_in6 addr1;
                                NetinetIn.sockaddr_in6 addr2;
                                addr1 = (NetinetIn.sockaddr_in6) iterator.ai_addr();
                                addr2 = (NetinetIn.sockaddr_in6) itr.ai_addr();
                                int t;
                                for (t = 0; t < 16; t++) {
                                    if (addr1.sin6_addr().s6_addr().read(t) != addr2.sin6_addr().s6_addr().read(t)) {
                                        break;
                                    }
                                }
                                if (t < 16) {
                                    itr = itr.ai_next();
                                    continue;
                                } else {
                                    skip = true;
                                    break;
                                }
                            }
                        } else if ((iterator.ai_family() != Socket.AF_INET()) && (iterator.ai_family() != Socket.AF_INET6())) {
                            /* we can't handle other family types */
                            skip = true;
                            break;
                        }
                        itr = itr.ai_next();
                    }
                    if (!skip) {
                        Netdb.addrinfo next = LibC.malloc(SizeOf.unsigned(Netdb.addrinfo.class));
                        if (next.isNull()) {
                            throw new OutOfMemoryError("malloc failed");
                        }
                        LibC.memcpy(next, iterator, SizeOf.unsigned(Netdb.addrinfo.class));
                        next.set_ai_next(WordFactory.nullPointer());
                        if (resNew.isNull()) {
                            resNew = next;
                        } else {
                            last.set_ai_next(next);
                        }
                        last = next;
                        i++;
                        if (iterator.ai_family() == Socket.AF_INET()) {
                            inetCount++;
                        } else if (iterator.ai_family() == Socket.AF_INET6()) {
                            inet6Count++;
                        }
                    }
                    iterator = iterator.ai_next();
                }
                retLen = i;
                iterator = resNew;
                ret = new InetAddress[retLen];
                if (Target_java_net_InetAddress.preferIPv6Address) {
                    /* AF_INET addresses will be offset by inet6Count */
                    inetIndex = inet6Count;
                    inet6Index = 0;
                } else {
                    /* AF_INET6 addresses will be offset by inetCount */
                    inetIndex = 0;
                    inet6Index = inetCount;
                }
                while (iterator.isNonNull()) {
                    int ret1;
                    if (iterator.ai_family() == Socket.AF_INET()) {
                        Inet4Address iaObj = Util_java_net_Inet4Address.new_Inet4Address();
                        JavaNetNetUtil.setInetAddress_addr(iaObj, NetinetIn.ntohl(((NetinetIn.sockaddr_in) iterator.ai_addr()).sin_addr().s_addr()));
                        JavaNetNetUtil.setInetAddress_hostName(iaObj, host);
                        ret[inetIndex] = iaObj;
                        inetIndex++;
                    } else if (iterator.ai_family() == Socket.AF_INET6()) {
                        // 455 jint scope = 0;
                        int scope = 0;
                        // 457 jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
                        Inet6Address iaObj = Util_java_net_Inet6Address.new_Inet6Address();
                        // 458 if (IS_NULL(iaObj)) {
                        if (iaObj == null) {
                            // 459 ret = NULL;
                            ret = null;
                            // 460 goto cleanupAndReturn;
                            return ret;
                        }
                        // 462 ret1 = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
                        ret1 = JavaNetNetUtil.setInet6Address_ipaddress(iaObj, ((NetinetIn.sockaddr_in6) iterator.ai_addr()).sin6_addr().s6_addr());
                        // 463 if (!ret1) {
                        if (!CTypeConversion.toBoolean(ret1)) {
                            // 464 ret = NULL;
                            ret = null;
                            // 465 goto cleanupAndReturn;
                            return ret;
                        }
                        // 468 scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
                        scope = ((NetinetIn.sockaddr_in6) iterator.ai_addr()).sin6_scope_id();
                        // 469 if (scope != 0) { /* zero is default value, no need to set */
                        if (scope != 0) {
                            /* zero is default value, no need to set */
                            // 470 setInet6Address_scopeid(env, iaObj, scope);
                            JavaNetNetUtil.setInet6Address_scopeid(iaObj, scope);
                        }
                        // 472 setInetAddress_hostName(env, iaObj, host);
                        JavaNetNetUtil.setInetAddress_hostName(iaObj, host);
                        // 473 (*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
                        ret[inet6Index] = iaObj;
                        // 474 inet6Index++;
                        inet6Index++;
                    }
                    iterator = iterator.ai_next();
                }
            }
        } finally {
            /* cleanupAndReturn: */
            Netdb.addrinfo iterator;
            Netdb.addrinfo tmp;
            iterator = resNew;
            while (iterator.isNonNull()) {
                tmp = iterator;
                iterator = iterator.ai_next();
                LibC.free(tmp);
            }
            Netdb.freeaddrinfo(res);
        }
    // JNU_ReleaseStringPlatformChars(env, host, hostname)
    // happens when I exit the CCharPointerHolder region.
    }
    return ret;
}
Also used : Netdb(com.oracle.svm.core.posix.headers.Netdb) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) Inet6Address(java.net.Inet6Address) NetinetIn(com.oracle.svm.core.posix.headers.NetinetIn) CCharPointerHolder(org.graalvm.nativeimage.c.type.CTypeConversion.CCharPointerHolder) InetAddress(java.net.InetAddress) CCharPointer(org.graalvm.nativeimage.c.type.CCharPointer) Substitute(com.oracle.svm.core.annotate.Substitute)

Example 63 with Inet6Address

use of java.net.Inet6Address in project JAirPort by froks.

the class ServiceInfoImpl method updateRecord.

/**
 * JmDNS callback to update a DNS record.
 *
 * @param dnsCache
 * @param now
 * @param rec
 */
@Override
public void updateRecord(DNSCache dnsCache, long now, DNSEntry rec) {
    if ((rec instanceof DNSRecord) && !rec.isExpired(now)) {
        boolean serviceUpdated = false;
        switch(rec.getRecordType()) {
            case // IPv4
            TYPE_A:
                if (rec.getName().equalsIgnoreCase(this.getServer())) {
                    _ipv4Addresses.add((Inet4Address) ((DNSRecord.Address) rec).getAddress());
                    serviceUpdated = true;
                }
                break;
            case // IPv6
            TYPE_AAAA:
                if (rec.getName().equalsIgnoreCase(this.getServer())) {
                    _ipv6Addresses.add((Inet6Address) ((DNSRecord.Address) rec).getAddress());
                    serviceUpdated = true;
                }
                break;
            case TYPE_SRV:
                if (rec.getName().equalsIgnoreCase(this.getQualifiedName())) {
                    DNSRecord.Service srv = (DNSRecord.Service) rec;
                    boolean serverChanged = (_server == null) || !_server.equalsIgnoreCase(srv.getServer());
                    _server = srv.getServer();
                    _port = srv.getPort();
                    _weight = srv.getWeight();
                    _priority = srv.getPriority();
                    if (serverChanged) {
                        _ipv4Addresses.clear();
                        _ipv6Addresses.clear();
                        for (DNSEntry entry : dnsCache.getDNSEntryList(_server, DNSRecordType.TYPE_A, DNSRecordClass.CLASS_IN)) {
                            this.updateRecord(dnsCache, now, entry);
                        }
                        for (DNSEntry entry : dnsCache.getDNSEntryList(_server, DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_IN)) {
                            this.updateRecord(dnsCache, now, entry);
                        }
                    // We do not want to trigger the listener in this case as it will be triggered if the address resolves.
                    } else {
                        serviceUpdated = true;
                    }
                }
                break;
            case TYPE_TXT:
                if (rec.getName().equalsIgnoreCase(this.getQualifiedName())) {
                    DNSRecord.Text txt = (DNSRecord.Text) rec;
                    _text = txt.getText();
                    serviceUpdated = true;
                }
                break;
            case TYPE_PTR:
                if ((this.getSubtype().length() == 0) && (rec.getSubtype().length() != 0)) {
                    _subtype = rec.getSubtype();
                    serviceUpdated = true;
                }
                break;
            default:
                break;
        }
        if (serviceUpdated && this.hasData()) {
            JmDNSImpl dns = this.getDns();
            if (dns != null) {
                ServiceEvent event = ((DNSRecord) rec).getServiceEvent(dns);
                event = new ServiceEventImpl(dns, event.getType(), event.getName(), this);
                dns.handleServiceResolved(event);
            }
        }
        // This is done, to notify the wait loop in method JmDNS.waitForInfoData(ServiceInfo info, int timeout);
        synchronized (this) {
            this.notifyAll();
        }
    }
}
Also used : InetAddress(java.net.InetAddress) Inet4Address(java.net.Inet4Address) Inet6Address(java.net.Inet6Address) ServiceEvent(javax.jmdns.ServiceEvent) Service(javax.jmdns.impl.DNSRecord.Service) Text(javax.jmdns.impl.DNSRecord.Text) Text(javax.jmdns.impl.DNSRecord.Text) Service(javax.jmdns.impl.DNSRecord.Service)

Example 64 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 {
    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        // ignore the request for favicon.ico
        return;
    }
    // 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)) + ".*.*";
    }
    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";
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");
    String url;
    if (System.getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) {
        // Check the System properties to determine if we are running on appengine or not
        // Google App Engine sets a few system properties that will reliably be present on a remote
        // instance.
        url = System.getProperty("ae-cloudsql.cloudsql-database-url");
        try {
            // Load the class that provides the new "jdbc:google:mysql://" prefix.
            Class.forName("com.mysql.jdbc.GoogleDriver");
        } catch (ClassNotFoundException e) {
            throw new ServletException("Error loading Google JDBC Driver", e);
        }
    } else {
        // Set the url with the local MySQL database connection url when running locally
        url = System.getProperty("ae-cloudsql.local-database-url");
    }
    log("connecting to: " + url);
    try (Connection conn = DriverManager.getConnection(url);
        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()) {
            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");
            }
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}
Also used : Inet4Address(java.net.Inet4Address) SQLException(java.sql.SQLException) Connection(java.sql.Connection) Inet6Address(java.net.Inet6Address) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) Date(java.util.Date) ServletException(javax.servlet.ServletException) ResultSet(java.sql.ResultSet) InetAddress(java.net.InetAddress) PrintWriter(java.io.PrintWriter)

Example 65 with Inet6Address

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

the class Server method getFirstNonLoopbackAddress.

/**
 * Get non-loopback address.  InetAddress.getLocalHost() does not work on machines without static ip address.
 *
 * @param ni target network interface
 * @param preferIPv4 true iff require IPv4 addresses only
 * @param preferIPv6 true iff prefer IPv6 addresses
 * @return nonLoopback {@link InetAddress}
 * @throws SocketException
 */
private static InetAddress getFirstNonLoopbackAddress(NetworkInterface ni, boolean preferIPv4, boolean preferIPv6) throws SocketException {
    InetAddress result = null;
    // skip virtual interface name, PTP and non-running interface.
    if (ni.isVirtual() || ni.isPointToPoint() || !ni.isUp()) {
        return result;
    }
    LOG.info("Interface name is: " + ni.getDisplayName());
    for (Enumeration en2 = ni.getInetAddresses(); en2.hasMoreElements(); ) {
        InetAddress addr = (InetAddress) en2.nextElement();
        if (!addr.isLoopbackAddress()) {
            if (addr instanceof Inet4Address) {
                if (preferIPv6) {
                    continue;
                }
                result = addr;
                break;
            }
            if (addr instanceof Inet6Address) {
                if (preferIPv4) {
                    continue;
                }
                result = addr;
                break;
            }
        }
    }
    return result;
}
Also used : Inet4Address(java.net.Inet4Address) Enumeration(java.util.Enumeration) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress)

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