本文以TCP为例。
1.Server端
绑定所有注册的地址,包括IPv4和IPv6 .
int nIndexSocket = 0 ;
SOCKET arrListenSocket[16];
char * pchPort = "8965" ;
ADDRINFOA sHints ;
PADDRINFOA psList = NULL ;
PADDRINFOA psTemp = NULL ;
memset(&sHints,0,sizeof(ADDRINFOA));
// 要获取绑定信息
sHints.ai_flags = AI_PASSIVE ; sHints.ai_family = AF_UNSPEC ;
sHints.ai_socktype = SOCK_STREAM ;
sHints.ai_protocol = IPPROTO_TCP ;
getaddrinfo(NULL,pchPort,&sHints,&psList);
psTemp = psList ;
while(psTemp && nIndexSocket <16)
{
arrListenSocket[nIndexSocket] = socket(psTemp->ai_family,psTemp->ai_socktype,psTemp->ai_protocol);
bind(arrListenSocket[nIndexSocket],psTemp->ai_addr,psTemp->ai_addrlen);
listen(arrListenSocket[nIndexSocket],5);
// 单独为每个Socket处理Accept...
HandleSocket(arrListenSocket[nIndexSocket]);
nIndexSocket ++ ;
psTemp = psTemp->ai_next ;
}
freeaddrinfo(psList);
SOCKET arrListenSocket[16];
char * pchPort = "8965" ;
ADDRINFOA sHints ;
PADDRINFOA psList = NULL ;
PADDRINFOA psTemp = NULL ;
memset(&sHints,0,sizeof(ADDRINFOA));
// 要获取绑定信息
sHints.ai_flags = AI_PASSIVE ; sHints.ai_family = AF_UNSPEC ;
sHints.ai_socktype = SOCK_STREAM ;
sHints.ai_protocol = IPPROTO_TCP ;
getaddrinfo(NULL,pchPort,&sHints,&psList);
psTemp = psList ;
while(psTemp && nIndexSocket <16)
{
arrListenSocket[nIndexSocket] = socket(psTemp->ai_family,psTemp->ai_socktype,psTemp->ai_protocol);
bind(arrListenSocket[nIndexSocket],psTemp->ai_addr,psTemp->ai_addrlen);
listen(arrListenSocket[nIndexSocket],5);
// 单独为每个Socket处理Accept...
HandleSocket(arrListenSocket[nIndexSocket]);
nIndexSocket ++ ;
psTemp = psTemp->ai_next ;
}
freeaddrinfo(psList);
2.Client端
void ConnectServer(const char * pchServerName,const char * pchServerPort)
{
ADDRINFOA sHints ;
PADDRINFOA psList ;
memset(&sHints,0,sizeof(ADDRINFOA));
sHints.ai_flags = AI_NUMERICHOST;
sHints.ai_family=AF_UNSPEC ;
sHints.ai_socktype = SOCK_STREAM ;
sHints.ai_protocol = IPPROTO_TCP ;
getaddrinfo(pchServerName,pchServerPort,&sHints,&psList);
SOCKET sock = socket(psList->ai_family,psList->ai_socktype,psList->ai_protocol);
connect(sock,psList->ai_addr,psList->ai_addrlen);
// sock : Send/Recv ....
closesocket(sock);
freeaddrinfo(psList)
}
{
ADDRINFOA sHints ;
PADDRINFOA psList ;
memset(&sHints,0,sizeof(ADDRINFOA));
sHints.ai_flags = AI_NUMERICHOST;
sHints.ai_family=AF_UNSPEC ;
sHints.ai_socktype = SOCK_STREAM ;
sHints.ai_protocol = IPPROTO_TCP ;
getaddrinfo(pchServerName,pchServerPort,&sHints,&psList);
SOCKET sock = socket(psList->ai_family,psList->ai_socktype,psList->ai_protocol);
connect(sock,psList->ai_addr,psList->ai_addrlen);
// sock : Send/Recv ....
closesocket(sock);
freeaddrinfo(psList)
}
使用IPv4连接:
使用IPv6连接:
ConnectServer("127.0.0.1","8965");
// ::1 表示Ipv6的回路地址.
ConnectServer("::1","8965");
ConnectServer("::1","8965");
转载于:https://blog.51cto.com/wangzai9931/164096