UDP datagram is being split on space character

765 views Asked by At

I am trying to get my head into SDLnet and I am encountering a problem where any UDP packets that I send from the client to the server are being broken up on the space character. I can't see any reason for this happening as I am not explicitly programming this behaviour in - I am literally just sending across a string.

The source code I am using is part of an online example on The Game Programming Wiki

Server

    printf("Fill the buffer\n>");
    scanf("%s", (char *)p->data);

    p->address.host = srvadd.host;  /* Set the destination host */
    p->address.port = srvadd.port;  /* And destination port */

    p->len = strlen((char *)p->data) + 1;
    SDLNet_UDP_Send(sd, -1, p); /* This sets the p->channel */

    /* Quit if packet contains "quit" */
    if (!strcmp((char *)p->data, "quit"))
        quit = 1;

Client

    /* Wait a packet. UDP_Recv returns != 0 if a packet is coming */
    if (SDLNet_UDP_Recv(sd, p))
    {
        printf("UDP Packet incoming\n");
        printf("\tChan:    %d\n", p->channel);
        printf("\tData:    %s\n", (char *)p->data);
        printf("\tLen:     %d\n", p->len);
        printf("\tMaxlen:  %d\n", p->maxlen);
        printf("\tStatus:  %d\n", p->status);
        printf("\tAddress: %x %x\n", p->address.host, p->address.port);

        /* Quit if packet contains "quit" */
        if (strcmp((char *)p->data, "quit") == 0)
            quit = 1;
    }       

Output

The output looks like this image.

The operating system I am running on is Windows 7 64-bit and I'm wondering if this could be something OS-related.

1

There are 1 answers

3
olevegard On BEST ANSWER

This is not the fault of UDP, it's go to do with the char* being split up when using scanf. ( I'm not a 100% sure about the details here. ) But as a general rule, in C, you shouldn't use scanf

Since you are using C++ ( at least according to the tags), you should do this the C++ way :

std::string msg = "";
std::cout << "Type a message and hit enter\n";

// Let user type a message
std::cin.ignore();
std::getline(std::cin, msg );

// UDPpacket uses Uint8, whereas msg.c_str() gives us a char*
// This simply copies the integer value of the chars into packet->data
memcpy(packet->data, msg.c_str(), msg.length() );

packet->len = msg.length();

Note : The std::cin.ignore(); is there to make sure we stop and wait for the user to type in the message.