I am experimenting with C++ winsockets. I want to create a method with which I can find the server on the network, without knowing it's IP. To do this I simply loop my connect method through IP adresses 192.168.1.0 to 192.168.1.255. However, the time between each connect is quite large, the program tends to wait at the: connect(nBytes, (sockaddr*)&server, sizeof(server)) statement for at least 30 seconds if not longer. My questions are the following: Why is this happening, how can I solve this and might there be an entirely different, better way to find the server?
my connect method:
SOCKET connect(char *ipAdress)
{
WSAData wsaData;
if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR)
return errorReport("Could not create startup struct");
nBytes = socket(AF_INET, SOCK_STREAM, 0);
if (nBytes == SOCKET_ERROR)
return errorReport("Socket could not be created");
struct hostent *host_entry;
if ((host_entry = gethostbyname(ipAdress)) == NULL)
return errorReport("Cannot find server.");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(1337);
server.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr;
if (connect(nBytes, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
WSACleanup();
return errorReport("Failed to connect to server.");
}
if (nBytes == -1)
{
WSACleanup();
disconnect(nBytes);
return errorReport("Could not connect");
}
return 0;
}
Also, feel free to tell me anything I'm doing wrong in the current connect method.