Jump to content

Send string data via UDP


Andreik
 Share

Recommended Posts

How can I send a string via UDP using C knowing that send function expect a pointer to a buffer containing the data to be transmitted. I tried to convert the string to a char buffer but some chars from original string are trimmed because contain some ASCII 0 chars. So, from initial 9 chars just 5 are sent.

char *sendbuffer = new char[packet.size()+1];
    sendbuffer[packet.size()] = 0;
    memcpy(sendbuffer,packet.c_str(),packet.size());

Is there any way to fix that?

When the words fail... music speaks.

Link to comment
Share on other sites

Are you saying packet.c_str() is not copied to sendbuffer?

I imagine your second parameter might not be what memcpy wants.

"Pointer to the source of data to be copied, type-casted to a pointer of type const void*."

EDIT:

Forget that, it does not seem to be the case.

But memcpy does not touch or care about null chars, it copies bytes, whatever they are, so only my question is relevant.

Are you not posting the relevant code to your question?

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

I specified in first post what method I try to send this data. Here it's the part involved in sending data. Check out last line that display how many bytes has been sent. It returns 5 bytes even sendbuffer it's 11 bytes.

iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
      cout << "WSAStartup failed: " << iResult << endl;
      return 1;
    }
    ConnectSocket = socket(AF_INET,SOCK_DGRAM,0);
    if (ConnectSocket == INVALID_SOCKET) {
        cout << "Error at socket: " << WSAGetLastError() << endl;
        WSACleanup();
        return 1;
    }
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = inet_addr(IPAddress);
    client.sin_port = htons(Port);
    iResult = connect(ConnectSocket,(SOCKADDR*) &client, sizeof(client));
    if ( iResult == SOCKET_ERROR) {
        closesocket (ConnectSocket);
        cout << "Unable to connect to server: " << WSAGetLastError() << endl;
        WSACleanup();
        return 1;
    }
    iResult = send( ConnectSocket, sendbuffer, (int)strlen(sendbuffer), 0 );
    if (iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    cout << "Bytes sent: " << iResult << endl;

When the words fail... music speaks.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...