无法使用UDP套接字c ++进行侦听

时间:2014-10-24 00:00:21

标签: c++ sockets udp

我正在尝试为服务器c ++文件实现UDP套接字。我有以下代码来设置套接字

//Create the server socket
    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
        throw "can't initialize socket";


    //Fill-in Server Port and Address info.
    sa.sin_family = AF_INET;
    sa.sin_port = htons(port);
    sa.sin_addr.s_addr = htonl(INADDR_ANY);


    //Bind the server port

    if (bind(s, (LPSOCKADDR)&sa, sizeof(sa)) == SOCKET_ERROR)
        throw "can't bind the socket";
    cout << "Bind was successful" << endl;

    //Successfull bind, now listen for client requests.

    if (listen(s, 10) == SOCKET_ERROR)
        throw "couldn't  set up listen on socket";
    else cout << "Listen was successful" << endl
            << "Waiting to be contacted for transferring files..." << endl;

当运行这段代码时,我到达最后一个if语句并且发生了SOCKET_ERROR,它会抛出&#34;无法设置侦听套接字&#34;。当我将其作为TCP连接时(如下所示),一切都正确设置:

 if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
        throw "can't initialize socket";

将SOCK_STREAM更改为SOCK_DGRAM会给我这个错误。有谁知道这里可能出现什么问题?

3 个答案:

答案 0 :(得分:2)

您无法侦听UDP套接字。请参阅文档:

  

sockfd参数是一个文件描述符,它引用SOCK_STREAM或SOCK_SEQPACKET类型的套接字。

答案 1 :(得分:1)

正如其他人所说,您不会将listen()(或accept())与UDP一起使用。调用bind()后,只需开始调用recvfrom()即可接收UDP数据包。

答案 2 :(得分:-1)

if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)对于设置UDP套接字

是正确的

要使用UDP套接字接收数据,您需要使用recvfrom()

示例:

// setup 
char RecvBuf[1024];
int BufLen = 1024;
sockaddr_in SenderAddr;
int SenderAddrSize = sizeof (SenderAddr);
// ........ 
if (recvfrom(s, RecvBuf, BufLen, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize) == SOCKET_ERROR) {..}