I'm coding a C application to connect with a router. The router does not filter any incoming connections, neither is behind any firewall. My problem is the C function "connect" returns SOCKET_ERROR, but the error message I get calling perror when this happens is: No error (¿?). That probably means I'm looking in the wrong direction (the place where perror gets the error msg from is not the place I'm interested in).
UPDATE: As suggested in comments, I called WSAGetLastError(), which returns 10061 (connection refused)
At same time, I have a web application that connects with the router and send it a json message via AJAX call. No problem at all. Using the same IP and same port to connect with.
If helps, the connect
function I'm using is defined at WinSock2.h. Working with Windows 7 Home Premium and Visual Studio 2010.
Those are what I consider relevant parts of the code (UPDATE: Added the missing part of socket initialization)
// 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;
}
So, why can I connect via AJAX call but the C connect function returns SOCKET_ERROR? Any clues?
Many thanks in advance
WSAGetLastError
to get the error code. – nwellnhofhints.ai_protocol = IPPROTO_TCP;
? – user2527098WSAStartup(MAKEWORD(2,2), &wsaData);
? – user2527098