'get mtu C++ portable way

Is there a way to get mtu C++ portable way? Like from both Linux and Windows ?

I know in Linux this is the code :

sys_get_mtu(const char *ifname)
{
    struct ifreq ifr;
    size_t ifnamelen;
    int s;

    ifnamelen = strlen(ifname);
    if (ifnamelen > sizeof(ifr.ifr_name) + 1)
        return 0;
    memcpy(ifr.ifr_name, ifname, ifnamelen);
    ifr.ifr_name[ifnamelen] = '\0';

    s = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (s == -1)
        return 0;
    if (ioctl(s, SIOCGIFMTU, &ifr) == -1) {
        close(s);
        return 0;
    }
    close(s);
    return ifr.ifr_mtu;
}



Solution 1:[1]

There is no portable way, because Windows does not fulfill the minimum POSIX compatibility requirement. You can, however, do some macro ninja techniques used by the C samurais.

On Linux and *BSD based systems.

#include <sys/ioctl.h>

struct ifreq res;

if (ioctl (s, SIOCGIFMTU, &res) != 0)
    // error case.

res.ifr_mtu;  //< MTU

On Windows, socket s is not necessarily an int.

#include <winsock.h>

DWORD mtu;

if (WSAGetIPUserMtu (s, &mtu) != 0)
    // error case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xsb