简体   繁体   中英

How to use the result of snprintf and send from server to client in socket programming C++

I have this function which prints the hmac of a string:

char *print_bits(unsigned char *bits, size_t len)
{
  int i;
  char buf[64], *put = buf;
  for(i = 0; i < len; i++){
  put += snprintf(put, 64, "%02x", bits[i]);
}
return put;
}

I want to use the result of printf and it send to my client app:

char buffer[64]
len = strlen(buffer);
    if(len < BUFFERSIZE)
         {
    gen_hmac_sha256(global_eid, (unsigned char *) buffer, len + 1);
    get_hmac_sha256(global_eid, hmac_sha256_out, HMAC_SHA256_LEN);
    printf("App.cpp: hmac sha256 hash: ");
    char *buffer2 = print_bits(hmac_sha256_out, 32);
    printf("\n");
    
    send(new_sock, buffer2, 64, 0);
}

However, send is not sending the result to the client. Thanks in advance for your help.

In your function print_bits , you are returning address to local variable/array. This will lead to undefined behaviour as you will be pointing to a memory region that you no longer have ownership and some other function/code can modify it.

Since, you are using C++ , you can write the same code using std::string .

std::string get_bits_str(unsigned char *bits, size_t len)
{
  std::stringstream stream;
  for(i = 0; i < len; i++){
      stream << std::hex << bits[i] << " ";
  return stream.str();
}

std::string buf = print_bits(hmac_sha256_out, 32);
printf("\n");
    
send(new_sock, buf.c_str(), 64, 0);

Create a buffer to hold the hmac string gotten from the print_bits function using snprintf as shown below:

char buf [64];
char *print_bits(unsigned char *bits, size_t len)
{
   int i;
   
   for(i = 0; i < len; i++){
     snprintf(buf+i*2, 3, "%02x", bits[i]);
    }
    return buf;
}

Then in the main function, use the send() system call as shown below to send from server to the client.

len = strlen(buffer);
if(len < BUFFERSIZE)
 {
     gen_hmac_sha256(global_eid, (unsigned char *) buffer, len + 1);
     get_hmac_sha256(global_eid, hmac_sha256_out, HMAC_SHA256_LEN);
     printf("App.cpp: hmac sha256 hash: ");
     send(new_sock, print_bits(hmac_sha256_out, 32), 64, 0); 
 }

Note that the hmac algorithm itself is executed inside Intel SGX and has not been shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM