Skip to content
Advertisement

python ctypes C++ get back char* missing last character on linux

i have the following C++ code:

__declspec(dllimport) char* get_mac()
{
    size_t byteToAlloc = 17;
    char *mac_addr = (char*) malloc(byteToAlloc);
    struct ifreq buffer;
    int s = socket(PF_INET, SOCK_DGRAM, 0);
    strcpy(buffer.ifr_name,"enp0s3");
    if (0 == ioctl(s, SIOCGIFHWADDR, &buffer))
    {
        // Save Mac Address in hex format
        snprintf(mac_addr, byteToAlloc, "%02X:%02X:%02X:%02X:%02X:%02X",
                    (unsigned char) buffer.ifr_hwaddr.sa_data[0],
                    (unsigned char) buffer.ifr_hwaddr.sa_data[1],
                    (unsigned char) buffer.ifr_hwaddr.sa_data[2],
                    (unsigned char) buffer.ifr_hwaddr.sa_data[3],
                    (unsigned char) buffer.ifr_hwaddr.sa_data[4],
                    (unsigned char) buffer.ifr_hwaddr.sa_data[5]);
    }
    close(s);
    return mac_addr;
}

which is using ifreq to get the mac address of the local PC and sticks it into a array of chars. The routine gets compiled in the “Utility.so”

Then i have the following python code:

from ctypes import *
mydll=cdll.LoadLibrary("./Utility.so")
mac_string = c_char_p(mydll.get_mac()).value
print mac_string

and i get the following result 02:00:AC:99:00:9

when my MAC is actually: 02:00:AC:99:00:9C

So im’ missing the last char.

any idea ?

NOTE: it works fine on both Mac and Windows !

please help.- greetings. cp

Advertisement

Answer

In C/C++, c-strings are NULL-terminated, which means the end is marked by a NULL (byte 0).

To store 17 chars of text (the length of the MAC), your array needs to be 18 characters, to account for that final NULL.

snprintf (http://www.cplusplus.com/reference/cstdio/snprintf/) will make sure it can write a NULL, so it is only writing 16 bytes of the MAC, and then the trailing NULL.

In short:

size_t byteToAlloc = 18;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement