Search code examples
csocketssend

how to send binary data through socket in c?


I'm trying to send binary data to the client, what I'm trying to do is: write(client_fd,"0xf",size,flag). I don't know how to make the string binary and not sure what type of flag should I use.


Solution

  • A string literal "0xf" is similar to

    char str[] = { '0', 'x', 'f', '\0' };
    

    If you want to write actual 0x0 and 0xf data, hex values can be expressed within a string literal, each with a leading \x like this:

    size = 2;
    nwritten = write(sock_fd, "\x0\xf", size);