我正在学习一个教我如何使用 win32 套接字(winsock2)的教程。我正在尝试创建一个连接到“localhost”的简单套接字,但是当我尝试连接到本地主机(在函数 connect() 处)时,我的程序失败了。
我需要管理员权限才能连接到本地主机吗?也许这就是它失败的原因?也许我的代码有问题?我已经尝试了端口 8888 和 8000,但它们都失败了。
此外,如果我将端口更改为 80 并连接到 www.google.com,我可以连接但我没有得到任何回复。那是因为我没有发送 HTTP 请求还是我打算得到一些响应?
这是我的代码(已删除包含):
// 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;
}