5

Linux ボックスでは、一般的なインターフェイス名は eth0、eth1 などのようになります。または同様の関数を使用して少なくとも 1 つの IP アドレスを見つける方法gethostbynameは知っていますが、IP アドレスが必要な名前付きインターフェイスを指定する方法がわかりません。の。ifconfig を使用して出力を解析することもできますが、この情報を大々的に調べるのは... 洗練されていないようです。

たとえば、すべてのインターフェイスとその IP アドレス (およびおそらく MAC アドレス) をコレクションに列挙する方法はありますか? または、少なくとも次のようなものgethostbyinterface("eth0")ですか?

4

2 に答える 2

10
// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

/**
 * getIPv4()
 *
 * This function takes a network identifier such as "eth0" or "eth0:0" and
 * a pointer to a buffer of at least 16 bytes and then stores the IP of that
 * device gets stored in that buffer.
 *
 * it return 0 on success or -1 on failure.
 *
 * Author:  Jaco Kroon <jaco@kroon.co.za>
 */
int getIPv4(const char * dev, char * ipv4) {
    struct ifreq ifc;
    int res;
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if(sockfd < 0)
        return -1;
    strcpy(ifc.ifr_name, dev);
    res = ioctl(sockfd, SIOCGIFADDR, &ifc);
    close(sockfd);
    if(res < 0)
        return -1;     
    strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr));
    return 0;
}


int main() {
    char ip[16];
    if(getIPv4("eth0", ip) == 0)
        printf("IPv4: %s\n", ip);
    else
        printf("No IP\n");
    return 0;
 }

更新:デッドリンクをコメントに移動し(後世のために)(@obayhanに感謝)、構文の強調表示を追加しました。

于 2008-11-03T17:59:19.390 に答える
3

編集:あなたが砲撃を好まないのを見ました. 次に、ifconfig がどのように機能するかを確認できます (/proc から少なくともいくつかの情報を抽出します)。

インターフェイス名がある場合は、これを(シェルで)実行できます。

ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'

インターフェイスを列挙するには、これを使用できます。

ifconfig | egrep '^[^ ]' | awk '{print $1}'

組み合わせ:

for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
  echo -n "${x}"
  echo -n "    "
  ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
done
于 2008-11-03T17:59:02.807 に答える