VMA92
VMA92

Reputation: 479

Unable to listen with UDP socket c++

I am trying to implement a UDP socket for a server c++ file. I have the following code to set up the socket

//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;

When running this code, I get up to the last if statement and a SOCKET_ERROR occurs which throws "couldn't set up listen on socket". When I have this as a TCP connection (as seen below) everything sets up properly:

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

Changing the SOCK_STREAM to SOCK_DGRAM gives me this error. Does anyone know what could be the issue here?

Upvotes: 1

Views: 5245

Answers (3)

John
John

Reputation: 3

if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) is correct for setting up a UDP Socket

For receiving data with a UDP socket, you need to use recvfrom()

Example:

// 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) {..}

Upvotes: -1

Remy Lebeau
Remy Lebeau

Reputation: 598309

As others have stated, you don't use listen() (or accept()) with UDP. After calling bind(), simply start calling recvfrom() to receive UDP packets.

Upvotes: 2

user207421
user207421

Reputation: 311054

You can't listen on a UDP socket. See the documentation:

The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET.

Upvotes: 2

Related Questions