2015-03-25 66 views
2

我有使用ioctl調用的ip,子網和廣播地址。 但不知道如何獲取默認網關和名稱服務器IP。 如果我從/etc/resolv.conf中選擇域名服務器,那麼它可靠嗎?如何在linux中使用ioctl獲取網關ip和nameserver ip

這裏是我的代碼:

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; 
} 
+1

由於內核不處理名稱解析,因此無法使用ioctl獲取名稱服務器。它生活在glibc圖書館的深處。 – myaut 2015-03-25 07:58:15

+0

@myaut:但是網關呢?那麼我從哪裏得到nameserver IP?你可以幫我嗎?? – 2015-03-25 08:43:18

+0

檢查以下代碼 - [鏈接](http://www.linuxquestions.org/questions/linux-networking-3/howto-find-gateway-address-through-code-397078/#post4913964) – 2015-03-25 08:54:39

回答

1

爲了讓您可以解析/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 

如果你需要的域名服務器地址,解析/etc/resolv.conf似乎是一個可靠的選擇我。

+0

請小心,當使用'/ etc/resolv.conf',在我的情況下,DHCPCD會覆蓋'/etc/resolv.conf'中列出的名稱服務器(執行'resolvconf -l')而不更新該文件。因此,使用的實際名稱服務器與配置中列出的名稱服務器不同。 – Yeti 2017-11-07 14:52:51

+0

@Yeti您可能已在您的DHCPCD配置中設置了「nohook resolv.conf」。該選項可防止DHCPCD更新文件。 – 2017-11-08 10:09:21