bind(...)总是使用WinSock2返回-1 - C ++

时间:2015-11-24 23:43:13

标签: c++ windows sockets winsock2

我正在用C ++为一个大学项目创建一个游戏,它需要一些使用套接字的网络功能。我的模块讲师给了我们工作(本地机器)客户端/服务器的示例代码,向我们展示它是如何工作的。他有以下设置套接字的代码,工作正常:

#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

#define SERVERIP     "127.0.0.1"
#define SERVERPORT   5555

void main(){
    WSADATA w;
    int error = WSAStartup(0x0202, &w);
    if (error != 0)
    {
        die("WSAStartup failed");
    }
    if (w.wVersion != 0x0202)
    {
        die("Wrong WinSock version");
    }

    // Create a TCP socket that we'll use to listen for connections.
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == INVALID_SOCKET)
    {
        die("socket failed");
    }

    // Fill out a sockaddr_in structure to describe the address we'll listen on.
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(SERVERIP);
    // htons converts the port number to network byte order (big-endian).
    serverAddr.sin_port = htons(SERVERPORT);

    // Bind the server socket to that address.
    if (bind(serverSocket, (const sockaddr *) &serverAddr, sizeof(serverAddr)) != 0)
    {
        die("bind failed");
    }
}

但是,当我复制大部分代码时,bind(...)函数会一直返回-1,而不是我讲师示例中的0。以下是我的代码的相关部分,使用类:

TCPSocket.h

#define SERVERIP     "127.0.0.1"
#define SERVERPORT   5555

#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

class TCPSocket {
public:
    TCPSocket();
    ~TCPSocket();

    void SetupServer(char* serverIP_, int serverPort_, int messageSize_);

protected:

private:

    SOCKET m_socket;
    sockaddr_in m_serverAddress;

    char* m_serverIP;
    int m_serverPort;
    int m_messageSize;
};

TCPSocket.cpp

TCPSocket::TCPSocket() {
    // Initialise WinSock Library, version 2.2
    WSADATA w;
    int error = WSAStartup(0x0202, &w);
    if(error != 0) {
        //error
        int i = 0;
    }
    if(w.wVersion != 0x0202) {
        //error
        int i = 0;
    }
}

void TCPSocket::SetupServer(char* serverIP_, int serverPort_, int messageSize_) {
    m_serverIP = serverIP_;
    m_serverPort = serverPort_;
    m_messageSize = messageSize_;

    // Create TCP socket
    m_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(m_socket == INVALID_SOCKET) {
        //error
        int i = 0;
    }

    m_serverAddress.sin_family = AF_INET;
    m_serverAddress.sin_addr.s_addr = inet_addr(SERVERIP);
    m_serverAddress.sin_port = htons(SERVERPORT);       // htons: port -> network byte order (big-endian)

    // Bind server socket to address
    int bindex = bind(m_socket, (const sockaddr *) &m_serverAddress, sizeof(m_serverAddress));
    if(bindex != 0) {
        //error
        int a = 0;
    }

}

1 个答案:

答案 0 :(得分:0)

正如我在评论中所说,我在所包含的代码的范围内犯了一个愚蠢的错误:基本上我在更新循环中运行SetupServer()函数,并且错误在第二次迭代中被捕获更新。除此之外,代码功能完备。