Sort-Key-IPv4

 view release on metacpan or  search on metacpan

IPv4.xs  view on Meta::CPAN

    UV ip = 0;
    while (1) {
        const char *start = p;
        int v = 0;
        while (*p >= '0' && *p <= '9') {
            v = v * 10 + (*p - '0');
            if (v > 255) return 0;
            p++;
        }
        if (p == start) return 0;
        ip = (ip << 8) + v;

        if (++i < 4) {
            if (*(p++) != '.') return 0;
        }
        else {
            if (*(p++) != sep) return 0;
            *out = ip;
            if (remainder) *remainder = p;
            return 1;
        }
    }
}

int
parse_len(pTHX_ const char *p, int *out) {
    int len = 0;
    const char *start = p;
    while ((*p >= '0') && (*p <= '9')) {
        len = len * 10 + *p - '0';
        if (len > 32) return 0;
        p++;
    }
    if ((*p != '\0') || (p == start)) return 0;
    *out = len;
    return 1;
}

MODULE = Sort::Key::IPv4		PACKAGE = Sort::Key::IPv4		
PROTOTYPES: DISABLE

UV
pack_ipv4(ipv4=NULL)
    SV *ipv4
PREINIT:
    const char *p;
CODE:
    if (!ipv4)
        ipv4 = DEFSV;
    if (!parse_ip(aTHX_ SvPV_nolen(ipv4), '\0', &RETVAL, NULL))
        Perl_croak(aTHX_ "bad IPv4 specification %s", SvPV_nolen(ipv4));
OUTPUT:
    RETVAL

void
pack_netipv4(netipv4=NULL)
    SV *netipv4
PREINIT:
    UV ip;
    const char *p;
PPCODE:
    if (!netipv4)
        netipv4 = DEFSV;
    if (parse_ip(aTHX_ SvPV_nolen(netipv4), '/', &ip, &p)) {
        int len;
        if (parse_len(aTHX_ p, &len)) {
            UV m = netmask[len];
            if ((ip & ~m) == 0) {
                XPUSHs(sv_2mortal(newSVuv(ip)));
                XPUSHs(sv_2mortal(newSVuv(m)));
                XSRETURN(2);
            }
        }
    }
    Perl_croak(aTHX_ "bad IPv4 network specification %s", SvPV_nolen(netipv4));



( run in 0.491 second using v1.01-cache-2.11-cpan-5511b514fd6 )