Connect()不起作用

时间:2013-10-29 18:11:48

标签: c++ winsock

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

我做错了什么?

1 个答案:

答案 0 :(得分:2)

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

为什么要两次致电WSAStartup()

除非必须指定本地端口(例如SMB协议),否则您不必使用bind()来执行connect()

有很多exemples on how to use WinSock to connect,请阅读它们。