1

我正在关注 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。

我究竟做错了什么?

4

1 回答 1

2

您无法连接到INADDR_ANY。指定 IP 地址。

为什么要打WSAStartup()两次电话?

并且您不必使用bind()来执行 a connect(),除非必须指定您的本地端口非常重要(如在 SMB 协议中)。

有很多关于如何使用 WinSock 连接的例子,阅读它们。

于 2013-10-29T18:16:45.610 回答