nim4n
nim4n

Reputation: 1829

text formatting with unsigned char

I'm very new in c++, my problem is I find a way to use printf for text formatting in output, but I can't find a way to format the text properly in string variable. My final goal is to save the current mac address in a string variable and compare it with another variable. This is my code:

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <iostream>

int main()
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
  char mac[6];
  int ret;
  strcpy(s.ifr_name, "enp5s0");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
      (unsigned char) s.ifr_hwaddr.sa_data[0],
      (unsigned char) s.ifr_hwaddr.sa_data[1],
      (unsigned char) s.ifr_hwaddr.sa_data[2],
      (unsigned char) s.ifr_hwaddr.sa_data[3],
      (unsigned char) s.ifr_hwaddr.sa_data[4],
      (unsigned char) s.ifr_hwaddr.sa_data[5]);
    if (mac_as_string == "28:d2:44:55:97:7f") {
    }
    return 0;
  }
  return 1;
}

I can't find a way to save mac address as string in mac_as_string variable.

Upvotes: 1

Views: 295

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Regarding the text formatting and creating a string variable the easiest way to go is using a std::ostringstream:

std::ostringstream macbuilder;

macbuilder << std::hex 
           << std::setw(2) << unsigned(s.ifr_hwaddr.sa_data[0]) << ':'
           << std::setw(2) << unsigned(s.ifr_hwaddr.sa_data[1]) << ':'
           << std::setw(2) << unsigned(s.ifr_hwaddr.sa_data[2]) << ':'
           << std::setw(2) << unsigned(s.ifr_hwaddr.sa_data[3]) << ':'
           << std::setw(2) << unsigned(s.ifr_hwaddr.sa_data[4]) << ':'
           << std::setw(2) << unsigned(s.ifr_hwaddr.sa_data[5];
std::string macaddr = macbuilder.str();

But if you just want to have a variable that is comparable with another one std::array<uint8_t,6> is the way to go:

std::array<uint8_t,6> macaddr {
    s.ifr_hwaddr.sa_data[0] ,
    s.ifr_hwaddr.sa_data[1] ,
    s.ifr_hwaddr.sa_data[2] ,
    s.ifr_hwaddr.sa_data[3] ,
    s.ifr_hwaddr.sa_data[4] ,
    s.ifr_hwaddr.sa_data[5] ,
    };

As mentioned std::array provides the operator==() and you could simply use that to compare with another variable created the same way.

Upvotes: 1

Related Questions