兼容ipv6的C/S架构详解
讲到ipv4如何兼容ipv6,我觉得首先得介绍一个函数, getaddrinfo()
头文件:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
函数原型:
int getaddrinfo(const char *node, //identify an Internet host
const char *service, //identify a service
const struct addrinfo *hints,
struct addrinfo **res);
getaddrinfo() returns one or more addrinfo structures, each of which contains an Internet address that can be specified in a call to bind() or connect().
addrinfo structure 如下:
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
hints指向一个addrinfo结构体,但是addrinfo结构体内有一个next指针,说明可以将addrinfo结构体拉成一条链表,具体作用不清楚,继续往下看。
继续往下看addrinfo这个结构体:
ai_family:specifies the desired address family,可以值为 AF_INET and AF_INET6,或者为AF_UNSPEC ,而AF_UNSPEC 表示getaddrinfo() should return socket addresses for any address family (either IPv4 or IPv6, for example) that can be used with node and service.
ai_socktype:specifies the preferred socket type,for example SOCK_STREAM or
SOCK_DGRAM.假如指定为0,表示任何类型都可以。
SOCK_STREAM表示有保障的(即能保证数据正确传送到对方)面向连接的SOCKET,基于TCP的,数据传输比较有保障
SOCK_DGRAM表示是无保障的面向消息的socket , 主要用于在网络上发广播信息。基于UDP的
ai_protocol: specifies the protocol for the returned socket addresses.假如指定为0,表示任何协议皆可以。 For example ip, tcp, or udp.
ai_flags:This field specifies additional options, described below. Multiple flags
are specified by logically OR-ing them together.for example, AI_V4MAPPED | AI_ADDRCONFIG。
All the other fields in the structure pointed to by hints must contain either 0 or a
null pointer, as appropriate. Specifying hints as NULL is equivalent to setting
ai_socktype and ai_protocol to 0; ai_family to AF_UNSPEC; and ai_flags to
(AI_V4MAPPED | AI_ADDRCONFIG).
浙公网安备 33010602011771号