Unix Network Programming Episode 24

Even if your system does not yet include support for IPv6, you can start using these newer functions by replacing calls of the form

foo.sin_addr.s_addr = inet_addr(cp);

with

inet_pton(AF_INET, cp, &foo.sin_addr);

and replacing calls of the form

ptr = inet_ntoa(foo.sin_addr);

with

char str[INET_ADDRSTRLEN];
ptr = inet_ntop(AF_INET, &foo.sin_addr, str, sizeof(str));

Simple version of inet_pton that supports only IPv4

int inet_pto(int family, const char *strptr, void *addrptr)
{
    if(family==AF_INET)
    {
        struct in_addr in_val;

        if(inet_aton(strptr, &in_val))
        {
            memcpy(addrptr, &in_val, sizeof(struct in_addr));
            return 1;
        }

        return 0;
    }

    errno=EAFNOSUPPORT;
    return -1;
}

Simple version of inet_pton that supports only IPv4

const char * inet_npto(int family, const char *strptr, char *strptr, size_t len)
{
    const u_char *p=(const u_char *)addrptr;

    if(family==AF_INET)
    {
        char temp[INET_ADDRSTRLEN];

        snprintf(temp, sizeof(tmp),"%d.%d.%d.%d",p[0],p[1],p[2],p[3]);
        if(strlen(temp)>=len)
        {
            errno=ENOSPC;
            return NULL;
        }

        strcpy(strptr, temp);
        return strptr;
    }

    errno=EAFNOSUPPORT;
    return NULL;
}

Simple version of inet_ntop that supports only IPv4

你可能感兴趣的:(Unix,Network,Programming)