WinSock无法连接
WinSock can not connect
我刚刚开始学习WinSock。我从阅读这篇文章开始:https://msdn.microsoft.com/en-us/library/windows/desktop/bb530750(v=vs.85).aspx我做了我被要求做的事。
但我无法连接,每次我运行这个程序时,我都会遇到同样的错误:
连接超时。连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为所连接的主机没有响应。
我的代码在这里:http://pastebin.com/0THqWKXv
你能告诉我我做错了什么吗?如何修复我的代码?
PS。IP地址是谷歌.pl
PS2。负责连接的实际代码:
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
while (iResult == SOCKET_ERROR){
cout << "Blad ustanowienia polaczenia:t" << WSAGetLastError() << endl;
ptr = ptr->ai_next;
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
}
在调用connect()
:之前,您应该调用getaddrinfo()
来解析地址
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(addr, nPort, &hints, &result);
if ( iResult != 0 )
{
printf("getaddrinfo failed with error: %dn", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next)
{
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
printf("socket failed with error: %ldn", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
我把地址改为"google.com",把端口改为"80",它就可以工作了。非常感谢!
相关文章:
- C++WinSock选择本地接口进行连接
- C++ TCP 服务器 (Winsock) 连接 (无效客户端) 然后立即关闭
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- Winsock客户端 - 通过TCP/IP4连接到网络摄像机
- Winsock C++连接超时
- 有没有办法方便地为 Winsock send() 生成 HTTP 标头,而不是手动连接字符串
- Winsock C++ - Java 连接速度慢
- Winsock 滞后,测试连接速度
- 使用Winsock API同时打开TCP连接
- 如何在 x 时间后中止 Winsock 连接
- WinSock无法连接
- C++WinSock蓝牙连接-AT命令-收到错误
- 使用Winsock创建SSL连接
- C++ Winsock 服务器-客户端远程连接
- c++winsock客户端无法使用主机IP的文本框进行连接
- 给所有连接的客户端的消息(Winsock)(c++)
- Winsock-正在将客户端重新连接到服务器-10061
- 从 QObject 继承类中的 winsock 连接函数
- winsock连接持续多久
- 尝试连接winsock时出现错误10061