winsock - 发件人UDP套接字未绑定到所需的端口

时间:2012-05-31 17:12:01

标签: udp winsock

下面你可以看到我的代码在C ++中用Winsock实现了一个非常基本的UDP发送器。问题在于,无论我运行多少次代码,socket(listenSocket)都绑定到不同的UDP端口。这有什么具体原因吗?我在代码中犯了一些错误吗?

感谢

#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

using namespace std;

int main(int argc, char *argv[])
{
    WSADATA wsaData;    
    SOCKADDR_IN myAddress;
    SOCKADDR_IN targetAddress;

    int myPort = 60888;
    const char *myIP = "192.168.0.1";
    int remotePort = 2048;
    const char *remoteIP = "192.168.0.2";

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET SendSocket = INVALID_SOCKET;
    SOCKET acceptSocket;

    char cBuffer[1024] = "Test Buffer";
    int nBytesSent = 0;
    int nBufSize = strlen(cBuffer);
    int iResult;

    // Initialize Winsock
    if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
    {
        cerr<<"Socket Initialization: Error with WSAStartup\n";
        system("pause");
        WSACleanup();
        exit(10);
    }

    ListenSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    if (ListenSocket == INVALID_SOCKET or SendSocket == INVALID_SOCKET)
    {
        cerr<<"Socket Initialization: Error creating socket"<<endl;
        system("pause");
        WSACleanup();
        exit(11);
    }

    //bind
    myAddress.sin_family = AF_INET;
    myAddress.sin_addr.s_addr = inet_addr(myIP);
    myAddress.sin_port = htons(myPort);

    targetAddress.sin_family = AF_INET;
    targetAddress.sin_addr.s_addr = inet_addr(remoteIP);
    targetAddress.sin_port = htons(remotePort);

    if(bind(ListenSocket, (SOCKADDR*) &myAddress, sizeof(myAddress)) == SOCKET_ERROR)
    {
        cerr<<"ServerSocket: Failed to connect\n";
        system("pause");
        WSACleanup();
        exit(14);
    }
    else
        printf("Server: bind() is OK.\n");

    nBytesSent = sendto(SendSocket, cBuffer, nBufSize, 0,
                 (SOCKADDR *) &targetAddress,
                 sizeof(SOCKADDR_IN));    

    printf("Everything is ok\n");

    system("PAUSE");

    closesocket(ListenSocket);
    closesocket(SendSocket);

    return EXIT_SUCCESS;
}
编辑:也许我不太清楚。我对此代码的处理方法是将一些数据发送到远程PC。但是,所需要的是UDP段应该看起来源自特定端口。如何才能做到这一点?我在这里做的不对吗?现在我正在考虑它,我想这确实是错的。 SendSocket和ListenSocket没有任何连接,对吗?那么,我怎样才能使UDP段看起来来自特定的UDP端口呢?谢谢!

1 个答案:

答案 0 :(得分:2)

在发送数据之前,你没有在bind()上调用SendSocket,因此WinSock可以自由地将该套接字绑定到它需要的任何随机本地IP /端口。如果必须每次都使用特定的源IP /端口发送数据,则必须首先bind()到该IP /端口。如果该本地IP /端口是您绑定ListenSocket的同一对,那么您不需要使用两个单独的套接字开始。您可以使用侦听传入数据的同一套接字发送数据。