ioctl(sock, SIOCGIFHWADDR, &ifr) fails with 1.7

Frédéric Bron frederic.bron@m4x.org
Fri Jun 12 12:30:00 GMT 2009


I used the following program to obtain mac address and ip of network
adpaters. It works fine with 1.5 but not with 1.7.

Output with 1.5:
sock=3
trying eth0
mac: 00.1f.3c.57.XX.XX, ip: XXX.XXX.XXX.XXX
trying eth1
mac: 00.1d.09.df.XX.XX, ip: XXX.XXX.XXX.XXX
trying eth2
mac: 08.00.27.00.XX.XX, ip: XXX.XXX.XXX.XXX
trying eth3
...

Output with 1.7:
sock=3
trying eth0
trying eth1
trying eth2
trying eth3
...

Any clue?

Frédéric

#include <iostream>
#include <iomanip>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>

void read_hwaddr(const struct ifreq &ifr) {
        std::cout << "mac: " ;
        const struct sockaddr &hwaddr=ifr.ifr_hwaddr ;
        for (size_t k=0 ; k<6 ; ++k) {
                if (k) std::cout << '.' ;
                unsigned int v=static_cast<unsigned char>(hwaddr.sa_data[k]) ;
                std::cout << std::hex << std::setw(2) <<
std::setfill('0') << static_cast<int>(v) ;
        }
}

void read_ip(const struct ifreq &ifr) {
        std::cout << "ip: " ;
        const struct sockaddr &addr=ifr.ifr_addr ;
        for (size_t k=0 ; k<4 ; ++k) {
                unsigned int v=static_cast<unsigned char>(addr.sa_data[k+2]) ;
                if (k) std::cout << '.' ;
                std::cout << std::dec << static_cast<int>(v) ;
        }
}

int main() {
        std::string eth("eth") ;
        struct protoent *proto=NULL ;
        if (proto=getprotobyname("tcp")) {
                int sock=socket(PF_INET, SOCK_STREAM, proto->p_proto) ;
                std::cout << "sock=" << sock << '\n' ;
                struct ifreq ifr ;
                for (char k='0' ; k<='9' ; ++k) {
                        std::cout << "trying " << (eth+k) << '\n' ;
                        std::memset(&ifr, 0, sizeof(struct ifreq)) ;
                        std::strcpy(ifr.ifr_name, (eth+k).c_str()) ;
                        // MAC address
                        if (ioctl(sock, SIOCGIFHWADDR, &ifr)!=0) continue ;
                        read_hwaddr(ifr) ;
                        std::cout << ", " ;
                        // IP address
                        if (ioctl(sock, SIOCGIFADDR, &ifr)==0) read_ip(ifr) ;
                        std::cout << '\n' ;
                }
                close(sock) ;
        }
        return 0 ;
}

--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/



More information about the Cygwin mailing list