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];


    sock = socket(AF_INET,SOCK_STREAM,0);
    if (sock < 0)
        return (-1);

        // 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)

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


        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. :)

6 Years
Discussion Span
Last Post by babzog

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);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.