Wednesday, January 10, 2007

interface list from OS

Ignorant as I am, I, for my life, could not determine how to get the interface list and their mask, address, MTU, etc from the operating system (from a C program).

So the first thought was obvious, to use PCAP. So I did. using pcap_findalldevs, combined with pcap_lookupnet would yield me all the interface names and the network portion of the local iIP address and broadcast address. Of course I spent good amount of time to figure that out.

So I went back to google code search to find an alternative. And I saw libnet. Seemd way too much work than what I wanted to do. And using system("ifconfig -a | grep *!)$!:!@"); was really not an option.

Finally I decided, enough was enough. And I downloaded ethereal source code. I wassure I have seen interface name, address, mac address etc on ethereal. So a little grepping "grep interface *" gave me the result I was looking for, it pointed to me that it was possible to get this info from the system from an IOCTL. DUH! I didn't know that. :(

So web search on "struct ifreq" got me to this little gem . Ofcrouse, from there on it wasnt that difficult to figure it all out. Even I could do that. Oh and considering how I always get stuck at displaying the sockaddr_in from the ifreq in human format, I found this nice package that showed me how to do it.
 printf( "addr [%s]\n",
inet_ntoa( ( (struct sockaddr_in *) &ifr->ifr_addr
)->sin_addr );

And finally, I attach the source that I managed to write using the techniques from the web.


cheers!

No comments: