【发布时间】:2014-02-27 11:18:05
【问题描述】:
我正在编写一个 C 应用程序来连接路由器。路由器不过滤任何传入连接,也不在任何防火墙后面。我的问题是 C 函数“connect”返回 SOCKET_ERROR,但发生这种情况时我调用 perror 时得到的错误消息是:没有错误(¿?)。这可能意味着我看错了方向(perror 从中获取错误消息的地方不是我感兴趣的地方)。
更新:按照 cmets 中的建议,我调用了 WSAGetLastError(),它返回 10061 (connection refused)
同时,我有一个与路由器连接并通过 AJAX 调用向其发送 json 消息的 Web 应用程序。完全没有问题。使用相同的IP和相同的端口连接。
如果有帮助,我正在使用的 connect 函数在 WinSock2.h 中定义。使用 Windows 7 家庭高级版和 Visual Studio 2010。
这些是我认为的相关代码部分(更新:添加了套接字初始化的缺失部分)
// Enters here
#ifdef WIN32
WSADATA wsaData;
int error = WSAStartup(MAKEWORD(2,0), &wsaData);
if(error != 0) return false;
if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0)
{
WSACleanup();
return false;
}
#endif
struct addrinfo hints;
struct addrinfo *m_data;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_socktype = SOCK_STREAM;
// hostname is a char * containing my IP, in the same subnetwork than the router,
// and I'm going to connect with 192.168.90.1 (connection correctly open) and port 5555
port = "5555";
getaddrinfo(hostname, port, &hints, &m_data);
int m_socket = socket(m_data->ai_family, m_data->ai_socktype, m_data->ai_protocol);
// more stuff here
if (connect(m_socket, (struct sockaddr *)m_data->ai_addr, m_data->ai_addrlen) == SOCKET_ERROR)
{
// I get "connection error: no error" here. Why?
perror("connection error");
closesocket(m_socket);
return false;
}
那么,为什么我可以通过 AJAX 调用连接,但 C 连接函数返回 SOCKET_ERROR?有什么线索吗?
在此先感谢
【问题讨论】:
-
使用
WSAGetLastError获取错误码。 -
得到 10061,根据msdn.microsoft.com/en-us/library/windows/desktop/… 表示“连接被拒绝”。但是 ajax 连接工作正常。
-
添加初始化套接字的缺失代码。
-
添加
hints.ai_protocol = IPPROTO_TCP;? -
尝试初始化 Winsock 2.2 版
WSAStartup(MAKEWORD(2,2), &wsaData);?