Why wont a simple socket to the localhost connect?
- by Jake M
I am following a tutorial that teaches me how to use win32 sockets(winsock2). I am attempting to create a simple socket that connects to the "localhost" but my program is failing when I attempt to connect to the local host(at the function connect()).
Do I need admin privileges to connect to the localhost? Maybe thats why it fails? Maybe theres a problem with my code? I have tried the ports 8888 & 8000 & they both fail.
Also if I change the port to 80 & connect to www.google.com I can connect BUT I get no response back. Is that because I haven't sent a HTTP request or am I meant to get some response back?
Here's my code (with the includes removed):
// Constants & Globals //
typedef unsigned long IPNumber; // IP number typedef for IPv4
const int SOCK_VER = 2;
const int SERVER_PORT = 8888; // 8888
SOCKET mSocket = INVALID_SOCKET;
SOCKADDR_IN sockAddr = {0};
WSADATA wsaData;
HOSTENT* hostent;
int _tmain(int argc, _TCHAR* argv[])
{
// Initialise winsock version 2.2
if (WSAStartup(MAKEWORD(SOCK_VER,2), &wsaData) != 0)
{
printf("Failed to initialise winsock\n");
WSACleanup();
system("PAUSE");
return 0;
}
if (LOBYTE(wsaData.wVersion) != SOCK_VER || HIBYTE(wsaData.wVersion) != 2)
{
printf("Failed to load the correct winsock version\n");
WSACleanup();
system("PAUSE");
return 0;
}
// Create socket
mSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (mSocket == INVALID_SOCKET)
{
printf("Failed to create TCP socket\n");
WSACleanup();
system("PAUSE");
return 0;
}
// Get IP Address of website by the domain name, we do this by contacting(??) the Domain Name Server
if ((hostent = gethostbyname("localhost")) == NULL) // "localhost" www.google.com
{
printf("Failed to resolve website name to an ip address\n");
WSACleanup();
system("PAUSE");
return 0;
}
sockAddr.sin_port = htons(SERVER_PORT);
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.S_un.S_addr = (*reinterpret_cast <IPNumber*> (hostent->h_addr_list[0]));
// sockAddr.sin_addr.s_addr=*((unsigned long*)hostent->h_addr); // Can also do this
// ERROR OCCURS ON NEXT LINE: Connect to server
if (connect(mSocket, (SOCKADDR*)(&sockAddr), sizeof(sockAddr)) != 0)
{
printf("Failed to connect to server\n");
WSACleanup();
system("PAUSE");
return 0;
}
printf("Got to here\r\n");
// Display message from server
char buffer[1000];
memset(buffer,0,999);
int inDataLength=recv(mSocket,buffer,1000,0);
printf("Response: %s\r\n", buffer);
// Shutdown our socket
shutdown(mSocket, SD_SEND);
// Close our socket entirely
closesocket(mSocket);
// Cleanup Winsock
WSACleanup();
system("pause");
return 0;
}