2011-01-11 110 views
1

有誰知道我如何獲得我的局域網IP並將其打印在屏幕上。 *我不是指shell,而是c編程。 **我會很感激,如果你會張貼我的示例代碼。獲取局域網ip並打印它

回答

3

<ifaddrs.h>getifaddrs()功能是獲取當前的接口和相應的地址,最簡單的方法:

#include <stdio.h> 
#include <ifaddrs.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 

int main() 
{ 
    struct ifaddrs *iflist, *iface; 

    if (getifaddrs(&iflist) < 0) { 
     perror("getifaddrs"); 
     return 1; 
    } 

    for (iface = iflist; iface; iface = iface->ifa_next) { 
     int af = iface->ifa_addr->sa_family; 
     const void *addr; 
     char addrp[INET6_ADDRSTRLEN]; 

     switch (af) { 
      case AF_INET: 
       addr = &((struct sockaddr_in *)iface->ifa_addr)->sin_addr; 
       break; 
      case AF_INET6: 
       addr = &((struct sockaddr_in6 *)iface->ifa_addr)->sin6_addr; 
       break; 
      default: 
       addr = NULL; 
     } 

     if (addr) { 
      if (inet_ntop(af, addr, addrp, sizeof addrp) == NULL) { 
       perror("inet_ntop"); 
       continue; 
      } 

      printf("Interface %s has address %s\n", iface->ifa_name, addrp); 
     } 
    } 

    freeifaddrs(iflist); 
    return 0; 
} 
4

有幾種方法;首先,您可以使用connect(2)建立與已知對等方的連接,然後使用getsockname(2)讀取本地套接字「名稱」。這是一個相當差的機制,但它很容易。

但是,getsockname(2)將只報告一個 IP地址,當一臺機器可能有上千個IP地址,並返回IP在您選擇的節點將部分取決於!所以,不是很可靠。

一個更好的答案是使用rtnetlink(7)直接從內核讀取機器的IP地址:您將發送RTM_GETADDR消息到機器上每個接口的內核並讀取答案。理解如何使用這個最好的選擇可能是讀取ip程序的源代碼。

另一種選擇是在IP套接字上使用SIOCGIFCONFioctl(2)。該接口不如rtnetlink(7)接口靈活,所以它可能並不總是正確的,但它將是一箇中間點。 ifconfig(8)實用程序使用此方法來顯示ifconfig -a輸出。再次,你最好的選擇將是閱讀來源。 (在ioctl_list(2)有一些輕微的文檔。)

+0

感謝..你知道我在哪裏可以找到示例代碼..? – azulay7 2011-01-11 11:27:37

+0

`getifaddrs()`是一個更易於使用的界面(它使用下面的netlink)。 – caf 2011-01-12 09:30:40

2

gethostbyname應該可以幫助你做到這一點。示例:

GetLocalAddress() 
{ 
    char ac[80]; 

    // Get my host name 
    if (gethostname(ac, sizeof(ac)) != -1) 
    { 
    printf("Host name: %s\n", ac); 

    // Find IP addresses 
    struct hostent* p_he = gethostbyname(ac); 

    if (p_he != 0) 
    { 
     for (int i=0; p_he->h_addr_list[i] != 0; ++i) 
     { 
      struct in_addr addr; 
      memcpy(&addr, p_he->h_addr_list[i], sizeof(struct in_addr)); 
      printf("IP address %d: %s\n", i, inet_ntoa(addr)); 
     } 
    } 
} 

您可能需要過濾以從列表中刪除127.0.0.1。

+1

我不認爲'C編程'有`std :: cout` ;-) – Johnsyweb 2011-01-11 11:56:11