我正在关注 c++ 网络教程winsock。
但是到目前为止我编写的代码并不能完全正常工作,我做错了什么?
my "main.cpp"
#include "main.h"
using namespace std;
int winsock()
{
//variables
const int winsock_version = 2;
WSAData wsa;
SOCKET sok;
SOCKADDR_IN server;
//start up
WSAStartup(MAKEWORD(winsock_version,0), &wsa);
sok = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//check startup
if(WSAStartup(MAKEWORD(winsock_version,0), &wsa) != 0)
{
cout << "An error occured during startup! \n";
WSACleanup();
return -1;
}
//check version
if (LOBYTE(wsa.wVersion) < winsock_version)
{
cout << "Your version of winsock is too low!\n";
cout << "\nWinsock 2.0 or above is required.";
return -1;
}
//check if socket is valid
if (sok == INVALID_SOCKET)
{
cout << "Invalid socket!";
return -1;
}
//set connection type
server.sin_family = AF_INET;
//set port
server.sin_port = htons(80);
//set adress to connect to
server.sin_addr.S_un.S_addr = INADDR_ANY;
//connect
connect(sok,(sockaddr*)(&server), sizeof(server));
//bind socket
bind(sok, (sockaddr*)(&server), sizeof(server));
if(connect(sok,(sockaddr*)(&server), sizeof(server)) !=0)
{
cout << "error during connecting! \n";
WSACleanup();
closesocket(sok);
return -1;
}
cout << "Connection was made!";
//clean up
WSACleanup();
closesocket(sok);
if (WSACleanup() !=0 || closesocket(sok) !=0)
{
cout << "Clean up failed! \n";
return -1;
}
return 0;
}
int main()
{
winsock();
}
和我的“main.h”
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
// std libs
#include <iostream>
#include <fstream>
#include <string>
//windows
#include <windows.h>
//networking libs
#include <winsock2.h>
// layout engine
#endif // MAIN_H_INCLUDED
当我运行程序时,它显示“连接期间出错!”,这意味着我有某种错误。
我使用 code::blocks 作为我的 IDE。
我究竟做错了什么?