Użyj getaddrinfo() i ustaw flagę podpowiedzi AI_NUMERICHOST, rodzina na AF_UNSPEC, po pomyślnym powrocie z getaddrinfo, wynikowym członkiem struct addrinfo .ai_family będzie albo AF_INET, albo AF_INET6.
EDIT mały przykład
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
struct addrinfo hint, *res = NULL;
int ret;
memset(&hint, '\0', sizeof hint);
hint.ai_family = PF_UNSPEC;
hint.ai_flags = AI_NUMERICHOST;
ret = getaddrinfo(argv[1], NULL, &hint, &res);
if (ret) {
puts("Invalid address");
puts(gai_strerror(ret));
return 1;
}
if(res->ai_family == AF_INET) {
printf("%s is an ipv4 address\n",argv[1]);
} else if (res->ai_family == AF_INET6) {
printf("%s is an ipv6 address\n",argv[1]);
} else {
printf("%s is an is unknown address format %d\n",argv[1],res->ai_family);
}
freeaddrinfo(res);
return 0;
}
$ ./a.out 127.0.0.1
127.0.0.1 is an ipv4 address
$ ./a.out ff01::01
ff01::01 is an ipv6 address
Wiem, że to nie jest część API gniazd, ale jeśli IP4 i IP6 są jedynymi możliwościami, nie możesz tego zrobić za pomocą 'strlen'? ;-) –
@Steve Jessop rozważyć np. ff02 :: 2 i 8.8.8.8 – nos
@nos: wystarczająco fair, nie zdawałem sobie sprawy, że ten pierwszy był prawidłowym adresem. Mówiąc bardziej ogólnie, czy istnieje sposób na zbadanie łańcuchów, to prostszy kod niż użycie API gniazd? W takim przypadku struktura zawierająca przeanalizowany adres nie jest potrzebna. –