给文本字符串是否是用标准C套接字API的IPv6地址或IPv4地址 [英] Tell whether a text string is an IPv6 address or IPv4 address using standard C sockets API
问题描述
我有哪里外部组件通过我这包含一个IP地址的字符串的程序。那么我就需要把它变成一个URI。对于IPv4这是容易的;我prePEND的http://和追加/。然而,对IPv6的我还需要围绕着它在方括号[]。
I have a program where an external component passes me a string which contains an IP address. I then need to turn it into a URI. For IPv4 this is easy; I prepend http:// and append /. However, for IPv6 I need to also surround it in brackets [].
有没有一个标准套接字API调用来确定地址的地址族?
Is there a standard sockets API call to determine the address family of the address?
推荐答案
使用的getaddrinfo ( ),并设置提示标志AI_NUMERICHOST,家庭AF_UNSPEC,在从的getaddrinfo全成归来,所产生的结构addrinfo中.ai_family成员将不是AF_INET或AF_INET6。
Use getaddrinfo() and set the hint flag AI_NUMERICHOST, family to AF_UNSPEC, upon successfull return from getaddrinfo, the resulting struct addrinfo .ai_family member will be either AF_INET or AF_INET6.
编辑,小例子
#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
这篇关于给文本字符串是否是用标准C套接字API的IPv6地址或IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!