Hey folks,

Probably a stupid error on my part, but I'm having trouble with this.

Using ioctl calls to get adapter info on a linux box. I've got it working using a fixed size array (of struct ifreq) but it's not working when I try to use a dynamic array of same.

//struct ifreq* ifreqs = NULL;
    struct ifreq ifreqs[100];

    struct ifconf ifconf;
    int sock, rval, iii, newSize, Iterations = 0;
    int numInterfaces = 0;
    char szAddress[18];

    memset(&ifconf,0,sizeof(ifconf));

    sock = socket(AF_INET,SOCK_STREAM,0);
    if (sock < 0)
    {
        perror("socket");
        return (-1);
    }

    do
    {
        // Calculate the new size, then allocate and assign the buffer.
//        newSize = 20 + (Iterations * 10);
//        ifreqs = new ifreq[newSize];
//        memset(ifreqs, 0, newSize);
        ifconf.ifc_req = ifreqs;
        ifconf.ifc_len = newSize;

        // Get the list of adapters on the system.
        if ((rval = ioctl(sock, SIOCGIFCONF, (char*)&ifconf)) < 0)
        {
            perror("ioctl(SIOGIFCONF)");
        }

        // Check for overflow.
//        if (ifconf.ifc_len == newSize)
//        {
//            delete [] ifreqs;
//            ifreqs = NULL;
//        }

        Iterations++;

        printf("ifc_len: %d, newSize: %d, Iterations: %d, MAX_TRIES: %d\n", ifconf.ifc_len, newSize, Iterations, MAX_TRIES);
    }
    while (ifconf.ifc_len == newSize && (Iterations < MAX_TRIES));

it works as it is now. If I comment out the fixed sized allocation of ifreqs and uncomment the currently commented out code (in the do..while loop), I get ifconf.ifc_len == 0.

I don't understand what I'm doing wrong in the dynamic allocation situation... hopefully it's a silly thing I've overlooked. :)

Ah.... spotted the error.

Forgot to factor in the size of struct ifreq. Doh! Knew it was a silly mistake!

This is the line I needed:

newSize = (20 + (Iterations * 10)) * sizeof(struct ifreq);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.