bool Connect() {
//初始化网络
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))
return false;
if (LOBYTE(wsadata.wVersion) != 2 ||
HIBYTE(wsadata.wVersion) != 2) {
printf("请求协议版本失败!\n");
return false;
}
//创建套接字
sock_client = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET_ERROR == sock_client) {
printf("创建socket失败!\n");
WSACleanup();
return false;
}
//解析域名为IP地址
hostent* p = gethostbyname(sHost.c_str());
if (p == NULL)
return false;//解析失败
//连接web服务器
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(80);//hrrp 默认端口80 https默认端口443
//IP地址
memcpy(&sa.sin_port, p->h_addr, 4);
if (SOCKET_ERROR == connect(sock_client, (sockaddr*)&sa, sizeof(sa)) )
{
cout << "服务器连接失败" << endl;
return false;
}
else
{
cout<<"服务器连接成功"<<endl;
return true;
}
}
这样会输出 服务器连接失败;
解决方法??
我才发现是我code写错了
if (SOCKET_ERROR == connect(sock_client, (sockaddr*)&sa, sizeof(sockaddr)) )
{
cout << "服务器连接失败" << endl;
return false;
}
else
{
cout<<"服务器连接成功"<<endl;
return true;
}
应该sizeof(sockaddr)而不是sa