windows xp下的ipv6地址转换
winsock2还没有关于ipv6的地址转换函数:inet_pton和inet_ntop
上网搜了一份实现的代码,如下:
#ifdef _WIN32
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
{
if (af == AF_INET)
{
struct sockaddr_in in;
memset(&in, 0, sizeof(in));
in.sin_family = AF_INET;
memcpy(&in.sin_addr, src, sizeof(struct in_addr));
getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
return dst;
}
else if (af == AF_INET6)
{
struct sockaddr_in6 in;
memset(&in, 0, sizeof(in));
in.sin6_family = AF_INET6;
memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
return dst;
}
return NULL;
}
int inet_pton(int af, const char *src, void *dst) //这个函数好像不行啊,
{
struct addrinfo hints, *res, *ressave;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = af;
if (getaddrinfo(src, NULL, &hints, &res) != 0)
{
cout<<"Couldn't resolve host: "<<src<<endl;
return -1;
}
ressave = res;
while (res)
{
memcpy(dst, res->ai_addr, res->ai_addrlen);
res = res->ai_next;
}
freeaddrinfo(ressave);
return 0;
}
#endif
//这个是可以用的
struct addrinfo hints = { 0 };
struct addrinfo *res;
int gai_err;
if(iptype==1) //根据ip类型选择地址族
hints.ai_family = AF_INET6;
else
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
gai_err = getaddrinfo(host,"9000",&hints,&res); //其中第二个参数自己设置啊
if(gai_err) return FALSE;
if(connect(sock,res->ai_addr,res->ai_addrlen) == SOCKET_ERROR) {//其实也可以用非阻塞socket实现,这里是阻塞socket去connect的,需要三次握手的
DWORD qq = WSAGetLastError();
return FALSE;
}
return TRUE;