// Convert a struct sockaddr address to a string, IPv4 and IPv6:
char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen, unsigned short *port)
{
    if (NULL == s || NULL == port) {
        return NULL;
    }
    switch(sa->sa_family) {
        case AF_INET:
            inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
                    s, maxlen);
            *port = ntohs(((struct sockaddr_in *)sa)->sin_port);
            break;

        case AF_INET6:
            inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
                    s, maxlen);
            *port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
            break;

        default:
            strncpy(s, "Unknown AF", maxlen);
            return NULL;
    }
    return s;
}
char *get_ip_str(struct sockaddr_storage *sa, char *s, size_t maxlen, unsigned short *port) {
    return get_ip_str((const struct sockaddr *)sa, s, maxlen, port);
}

发表评论