SDL_net icon indicating copy to clipboard operation
SDL_net copied to clipboard

Proposal: MAC Address

Open namandixit opened this issue 1 year ago • 3 comments

Would there be interest in adding a function to get the MAC address of the machine in SDL? This would be useful in calculating UUIDv1. I could contribute the Windows version, but wanted to know if it is desired (and if yes, should it go here or in SDL_net).

namandixit avatar Oct 08 '24 23:10 namandixit

Not here, maybe it makes sense in SDL_net?

slouken avatar Oct 08 '24 23:10 slouken

I don’t know if I’ll add this yet, but I’ve moved this to SDL_net and reopened it for now.

icculus avatar Oct 09 '24 13:10 icculus

Here is a pass at Windows version, putting it here instead of filing a PR since it's not clear if it belongs in SDL:

#include <Windows.h>
#include <iphlpapi.h>
#pragma comment(lib, "Iphlpapi.lib")
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")

// Parameter is an array of size 6
bool macGetFromArbitraryNIC (unsigned char mac[])
{
    static bool is_cached = false;
    static unsigned char mac_cached[6];

    if (!is_cached) {
        IP_ADAPTER_INFO adapters[64]; // Maximum number of adapters we want to iterate over
        DWORD adapters_size = sizeof(adapters);

        DWORD status = GetAdaptersInfo(adapters, &adapters_size);
        if (status == ERROR_SUCCESS) {
            PIP_ADAPTER_INFO adapt = &adapters[0];

            do {
                if (((adapt->Type == MIB_IF_TYPE_ETHERNET) ||
                     (adapt->Type == IF_TYPE_IEEE80211)) &&
                    !StrStrIA(adapt->Description, "virtual")) {
                    CopyMemory(mac,        adapt->Address, 6);
                    CopyMemory(mac_cached, adapt->Address, 6);

                    is_cached = true;

                    return true; // If MAC found
                }

                adapt = adapt->Next;
            } while (adapt);

            return false; // If no valid MAC found
        } else {
            return false; // If couldn't get information about NICs
        }
    } else {
        CopyMemory(mac, mac_cached, 6);

        return true; // If MAC is already cached
    }
}

Different runs of the application may return different MACs (due to NICs appearing in different order), but fixing that will require too much overhead. Also, we filter out address for virtual NICs since they may be same on different machines.

namandixit avatar Oct 10 '24 03:10 namandixit

Passing on this.

icculus avatar Aug 07 '25 03:08 icculus