I have got ip, subnet and broadcast address using ioctl call. but don't know how to get default gateway and nameserver ip. if I pick nameserver from /etc/resolv.conf
then is it reliable?
Here is my code:
int main(void)
{
char buf[1024];
struct ifconf ifc;
struct ifreq *ifr;
int sck, nInterfaces;
int i;
unsigned char mac[6];
sck = socket(AF_INET, SOCK_DGRAM, 0);
if(sck < 0)
{
perror("socket");
return 1;
}
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if(ioctl(sck, SIOCGIFCONF, &ifc) < 0)
{
perror("ioctl(SIOCGIFCONF)");
return 1;
}
ifr = ifc.ifc_req;
nInterfaces = ifc.ifc_len / sizeof(struct ifreq);
for(i = 0; i < nInterfaces; i++)
{
struct ifreq *item = &ifr[i];
printf("Interface Name = %s\nIP = %s\n",
item->ifr_name,
inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr));
ioctl(sck, SIOCGIFNETMASK, item);
printf("SubNet Mask = %s\n", inet_ntoa(((struct sockaddr_in *)&item->ifr_netmask)->sin_addr));
ioctl(sck, SIOCGIFBRDADDR, item);
printf("BroadCat Address = %s\n", inet_ntoa(((struct sockaddr_in *)&item->ifr_broadaddr)->sin_addr));
ioctl(sck, SIOCGIFHWADDR, item);
memcpy(mac, item->ifr_hwaddr.sa_data, 6);
printf("MAC:%02X:%02X:%02X:%02X:%02X:%02X\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
}
return 0;
}
To get the default gateway you can parse /proc/net/route
:
# cat /proc/net/route
Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
eth0 00000000 010110AC 0003 0 0 0 000000000 0 0
If you need nameserver address, parsing /etc/resolv.conf
seems like a reliable option to me.
You can use
struct rtentry route;
(...)
ioctl(sck, SIOCADDRT, &route)
More information her:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.