如何使用客户端套接字绑定

时间:2013-02-01 09:32:25

标签: c++ sockets network-programming winsock

我正在编写一个Socket库,我遇到了绑定到特定地址和端口的客户端套接字的问题。我正在测试我的winsock TCP库,虽然我确定我没有理由在* nix上遇到同样的问题。到目前为止一切正常(如果我connect()没有先致电bind()我可以send()recv())。

我有一台服务器正在侦听192.168.1.99:XXXX(我机器的地址)。

然后我得到一个套接字并绑定到192.168.1.99:0。我尝试连接时收到套接字错误10049(WSAEADDRNOTAVAIL)。如果我尝试绑定到0.0.0.0:0,就会发生同样的事情。

如果我尝试绑定到127.0.0.1:0或localhost或将主机名保留为NULL(如果这是可能的话,我应该使用AI_PASSIVE标志吗?)然后连接我得到10061(WSACONNREFUSED )。

有人知道这样做的正确方法吗?

EDIT3:结果问题是我在调用bind之前调用socket,然后在调用connect之前再次调用它。我在调用bind之前将它切换到只调用套接字。我不知道是否有其他人对这整个概念感到困惑,所以除非有人认为应该关闭,否则我会把它留在这里?

编辑2:我的插座是两次问题吗?

编辑:以下是一些功能

int main() {
    WSADATA wsaData;   // if this doesn't work

    if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0) {
        cout << WSAStartup failed << endl;
        return -1;
    }

    ClientSocket* cs = new ClientSocket("192.168.1.99", "XXXX");

    cs->bind("", "0"); //error 10049 (WSAEADDRNOTAVAIL)
    //cs->bind("", "60000"); //error 10049 (WSAEADDRNOTAVAIL)

    //cs->bind("0.0.0.0", "0"); //error 10049 (WSAEADDRNOTAVAIL)
    //cs->bind("0.0.0.0", "60000"); //error 10049 (WSAEADDRNOTAVAIL)

    //cs->bind("192.168.1.99", "0"); //error 10061 (WSACONNREFUSED)
    //cs->bind("192.168.1.99", "60000"); //error 10061 (WSACONNREFUSED)

    //cs->bind("127.0.0.1", "0"); //error 10061 (WSACONNREFUSED)
    //cs->bind("127.0.0.1", "60000"); //error 10061 (WSACONNREFUSED)

    //cs->bind("localhost", "0"); //error 10061 (WSACONNREFUSED)
    //cs->bind("localhost", "60000"); //error 10061 (WSACONNREFUSED)


    cs->connect(); //connects to the info passed in ctor

    Socket* s = cs->getSocket();

    if(s == NULL) {
        cs->close();
        return -1;
    }

    .
    .
    .
    .
}

//these are the methods exposed by my API
int ClientSocket::bind(std::string hostname, std::string port) {
    if(bound) {
        return -1;
    }
    if(connected) {
        return -2;
    }

    //this defines what specialSockOp will do
    ssop = &ClientSocket::BaseDef::bind;

    info->hostname = hostname;
    if(hostname.compare("") == 0) {
        info->AI_FLAG_PASSIVE = true;
    }
    info->port = port;

    //calls SpecialSocket::socket()
    socket();

    bound = true;

    return 0;
}

int ClientSocket::connect() {
    if(connected) {
        return SOCKET_ERROR;
        //throw exception
    }
    if(bound) {
        ssop = &ClientSocket::BaseDef::connect;
    }
    socket();
    return 0;
}

void SpecialSocket::WinImp::socket() {
    struct addrinfo *results = NULL, *p = NULL, hints;
    int rv;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = (containerClass->info->ipType == IP_DUAL ? AF_UNSPEC :
        containerClass->info->ipType == IPV6 ? AF_INET6 : AF_INET);
    hints.ai_socktype = (containerClass->info->protocol == TCP ? SOCK_STREAM : 
        SOCK_DGRAM);
    hints.ai_protocol = 0;
    if(containerClass->info->AI_FLAG_PASSIVE) {
        hints.ai_flags |= AI_PASSIVE;
    }
    if(containerClass->info->AI_FLAG_CANONNAME) {
        hints.ai_flags |= AI_CANONNAME;
    }

    //cStringHostname returns NULL if an empty string has been passed in
    if((rv = getaddrinfo(containerClass->info->cStringHostname(),
         containerClass->info->cStringPort(), &hints, &results)) != 0) {
            //throw exception
    }

    for(p = results; p != NULL; p = p->ai_next) {
        if((containerClass->info->sock_fd = ::socket(p->ai_family,
                 p->ai_socktype, p->ai_protocol)) == INVALID_SOCKET) {
            closesocket(containerClass->info->sock_fd);
            continue;
        }

        //for a ClientSocket specialSockOp will call either bind or connect
        //corresponding to the function called by ClientSocket
        if(containerClass->specialSockOp(p->ai_addr) == SOCKET_ERROR) {
            closesocket(containerClass->info->sock_fd);
            continue;
        }

        break; //successfully connected
    }

    if(p == NULL) {
        //none of the connections in results were good
        //throw exception - could not connect
    }

    freeaddrinfo(results);
}

int SpecialSocket::WinImp::bind(const void* addr) {
    struct sockaddr* ai_addr = (struct sockaddr*)addr;

    return ::bind(containerClass->getSockFd(), ai_addr, sizeof(*ai_addr));

}

int ClientSocket::WinImp::connect(const void* addr) {
    struct sockaddr* ai_addr = (struct sockaddr*)addr;

    int result = ::connect(containerClass->getSockFd(), ai_addr, sizeof(*ai_addr));

    if(result == SOCKET_ERROR) {
        //these are where my errors are showing up
        cout << "error after connect() is - " << WSAGetLastError() << endl;
        return SOCKET_ERROR;
    }

    containerClass->servInfo->sock_fd = containerClass->getSockFd();

    //I separated the functionality here - Socket can only send/recv
    containerClass->s = new Socket();
    //I use getpeername here to get information about the remote socket

    //Long story but basically sets up the Socket
    containerClass->initRWSocket(containerClass->s, containerClass->servInfo);

    return result;
}

然后,用户可以致电ClientSocket.getSocket(),然后返回Socket,然后他们才能send/recv开启。在我的情况下,这是返回NULL,因为Socket从未实例化,因为SpecialSocket::connect在它执行之前返回。

1 个答案:

答案 0 :(得分:3)

您必须绑定到能够连接到connect的目标地址的有效本地地址,即具有到它的路由。显然在这种情况下:

  • 192.168.1.99不是本地地址,而是远程地址
  • 127.0.0.1是本地地址,但您只能从中获得127.0.0.1,而不是任何远程地址
  • 0.0.0.0是侦听套接字的有效绑定地址,但不适用于活动(出站)套接字。

这是绑定活动套接字是个坏主意的几个原因之一:在多宿主主机中,您必须迭代本地地址以选择合适的主机,即复制TCP将自动为您执行的路由。你根本没有做bind()。

编辑中给出的解释与您得到的错误不一致。