在ANSI C中获取给定IP地址的网关

21

我已经疯狂地搜索了一圈,却没有得到一个真正的答案。我找到了一个例子,但它依赖于个人自己的库,所以用处不是很大。

起初我想要获取接口的默认网关,但由于不同的IP可能被路由到不同的地方,我很快就明白了我想要做的是通过使用AF_ROUTE套接字和rtm_type RTM_GET,获取给定目标IP使用的网关。 有没有人能提供一个例子,让我最终获得一个包含网关IP(或MAC地址)的字符串?网关条目似乎是十六进制的,但也被编码在/proc/net/route中,我猜AF_ROUTE套接字从那里获取信息(但是通过内核获取)。

谢谢您的帮助

还有附言: 我刚开始使用Stack Overflow,我必须说,你们所有人都太棒了!快速回复且有用!你们是我的新朋友 ;)

3个回答

27

这是与操作系统相关的内容,没有统一(或ANSI C)API。

假设在Linux上,最好的方法是解析/proc/net/route,查找目标为00000000的条目,在网关列中可以读取网关IP地址的十六进制表示(我认为是大端)

如果您想通过更具体的API调用来完成此操作,则需要进行相当多的操作,以下是一个示例程序:

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


#define BUFSIZE 8192
char gateway[255];

struct route_info {
    struct in_addr dstAddr;
    struct in_addr srcAddr;
    struct in_addr gateWay;
    char ifName[IF_NAMESIZE];
};

int readNlSock(int sockFd, char *bufPtr, int seqNum, int pId)
{
    struct nlmsghdr *nlHdr;
    int readLen = 0, msgLen = 0;

 do {
    /* Recieve response from the kernel */
        if ((readLen = recv(sockFd, bufPtr, BUFSIZE - msgLen, 0)) < 0) {
            perror("SOCK READ: ");
            return -1;
        }

        nlHdr = (struct nlmsghdr *) bufPtr;

    /* Check if the header is valid */
        if ((NLMSG_OK(nlHdr, readLen) == 0)
            || (nlHdr->nlmsg_type == NLMSG_ERROR)) {
            perror("Error in recieved packet");
            return -1;
        }

    /* Check if the its the last message */
        if (nlHdr->nlmsg_type == NLMSG_DONE) {
            break;
        } else {
    /* Else move the pointer to buffer appropriately */
            bufPtr += readLen;
            msgLen += readLen;
        }

    /* Check if its a multi part message */
        if ((nlHdr->nlmsg_flags & NLM_F_MULTI) == 0) {
           /* return if its not */
            break;
        }
    } while ((nlHdr->nlmsg_seq != seqNum) || (nlHdr->nlmsg_pid != pId));
    return msgLen;
}
/* For printing the routes. */
void printRoute(struct route_info *rtInfo)
{
    char tempBuf[512];

/* Print Destination address */
    if (rtInfo->dstAddr.s_addr != 0)
        strcpy(tempBuf,  inet_ntoa(rtInfo->dstAddr));
    else
        sprintf(tempBuf, "*.*.*.*\t");
    fprintf(stdout, "%s\t", tempBuf);

/* Print Gateway address */
    if (rtInfo->gateWay.s_addr != 0)
        strcpy(tempBuf, (char *) inet_ntoa(rtInfo->gateWay));
    else
        sprintf(tempBuf, "*.*.*.*\t");
    fprintf(stdout, "%s\t", tempBuf);

    /* Print Interface Name*/
    fprintf(stdout, "%s\t", rtInfo->ifName);

    /* Print Source address */
    if (rtInfo->srcAddr.s_addr != 0)
        strcpy(tempBuf, inet_ntoa(rtInfo->srcAddr));
    else
        sprintf(tempBuf, "*.*.*.*\t");
    fprintf(stdout, "%s\n", tempBuf);
}

void printGateway()
{
    printf("%s\n", gateway);
}
/* For parsing the route info returned */
void parseRoutes(struct nlmsghdr *nlHdr, struct route_info *rtInfo)
{
    struct rtmsg *rtMsg;
    struct rtattr *rtAttr;
    int rtLen;

    rtMsg = (struct rtmsg *) NLMSG_DATA(nlHdr);

/* If the route is not for AF_INET or does not belong to main routing table
then return. */
    if ((rtMsg->rtm_family != AF_INET) || (rtMsg->rtm_table != RT_TABLE_MAIN))
        return;

/* get the rtattr field */
    rtAttr = (struct rtattr *) RTM_RTA(rtMsg);
    rtLen = RTM_PAYLOAD(nlHdr);
    for (; RTA_OK(rtAttr, rtLen); rtAttr = RTA_NEXT(rtAttr, rtLen)) {
        switch (rtAttr->rta_type) {
        case RTA_OIF:
            if_indextoname(*(int *) RTA_DATA(rtAttr), rtInfo->ifName);
            break;
        case RTA_GATEWAY:
            rtInfo->gateWay.s_addr= *(u_int *) RTA_DATA(rtAttr);
            break;
        case RTA_PREFSRC:
            rtInfo->srcAddr.s_addr= *(u_int *) RTA_DATA(rtAttr);
            break;
        case RTA_DST:
            rtInfo->dstAddr .s_addr= *(u_int *) RTA_DATA(rtAttr);
            break;
        }
    }
    //printf("%s\n", inet_ntoa(rtInfo->dstAddr));

    if (rtInfo->dstAddr.s_addr == 0)
        sprintf(gateway, (char *) inet_ntoa(rtInfo->gateWay));
    //printRoute(rtInfo);

    return;
}


int main()
{
    struct nlmsghdr *nlMsg;
    struct rtmsg *rtMsg;
    struct route_info *rtInfo;
    char msgBuf[BUFSIZE];

    int sock, len, msgSeq = 0;

/* Create Socket */
    if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
        perror("Socket Creation: ");

    memset(msgBuf, 0, BUFSIZE);

/* point the header and the msg structure pointers into the buffer */
    nlMsg = (struct nlmsghdr *) msgBuf;
    rtMsg = (struct rtmsg *) NLMSG_DATA(nlMsg);

/* Fill in the nlmsg header*/
    nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));  // Length of message.
    nlMsg->nlmsg_type = RTM_GETROUTE;   // Get the routes from kernel routing table .

    nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;    // The message is a request for dump.
    nlMsg->nlmsg_seq = msgSeq++;    // Sequence of the message packet.
    nlMsg->nlmsg_pid = getpid();    // PID of process sending the request.

/* Send the request */
    if (send(sock, nlMsg, nlMsg->nlmsg_len, 0) < 0) {
        printf("Write To Socket Failed...\n");
        return -1;
    }

/* Read the response */
    if ((len = readNlSock(sock, msgBuf, msgSeq, getpid())) < 0) {
        printf("Read From Socket Failed...\n");
    return -1;
    }
/* Parse and print the response */
    rtInfo = (struct route_info *) malloc(sizeof(struct route_info));
//fprintf(stdout, "Destination\tGateway\tInterface\tSource\n");
    for (; NLMSG_OK(nlMsg, len); nlMsg = NLMSG_NEXT(nlMsg, len)) {
        memset(rtInfo, 0, sizeof(struct route_info));
        parseRoutes(nlMsg, rtInfo);
    }
    free(rtInfo);
    close(sock);

    printGateway();
    return 0;
}

非常好的工作示例,谢谢。虽然它只提供了IPv4网关,但可以进行调整以查找IPv6网关(如果有人想知道的话)。 - jdknight
这段代码在一个我们找不到任何原因的平台上返回空值。首先,我们执行"netstat"命令,可以看到系统中定义了一个网关地址。然而,上面的代码片段并没有为我们提供任何网关地址。当我们调试代码时,我们注意到内核路由表在套接字的接收函数中没有提供任何信息(我认为直接提供EOF): if ((readLen = recv(sockFd, bufPtr, BUFSIZE - msgLen, 0)) < 0) { perror("SOCK READ: "); return -1; } - bugra
对此有任何评论吗? - bugra
在Linux下,“route”工具的实现使用“/proc/net/route”文件。还有一个注释说“AF_NETLINK”接口是虚假的。然而,我并不清楚如何在没有套接字的情况下修改表格... - Alexis Wilke
有没有办法获取IP范围(如果目标地址是fe80 :: / 64,如何获取64)?在属性类型上进行了谷歌搜索,但找不到任何信息。 - Possible
显示剩余2条评论

6

也许这是一个很老的问题,但我遇到了同样的问题,并且找不到更好的结果。最终,我用这些代码解决了我的问题,它有一些变化。所以我决定分享它。

char* GetGatewayForInterface(const char* interface) 
{
    char* gateway = NULL;

    char cmd [1000] = {0x0};
    sprintf(cmd,"route -n | grep %s  | grep 'UG[ \t]' | awk '{print $2}'", interface);
    FILE* fp = popen(cmd, "r");
    char line[256]={0x0};

    if(fgets(line, sizeof(line), fp) != NULL)
        gateway = string(line);


    pclose(fp);
}

如果您想获取默认路由,可以将命令替换为 ip route | grep default | awk '{print $3}' 并删除 const char* interface - Nathan F.
@Fisc 在许多系统上,如果不使用-n命令行标志来使用route命令,将无法正常工作,因为某些IP地址没有相应的名称,对于每个这样的IP地址,它都必须超时等待。这将会非常缓慢。 - Alexis Wilke

2
我决定采用“快速而简单”的方式开始,并使用netstat -rm/proc/net/route中读取IP地址。
我想分享我的功能... 但请注意,其中存在一些错误,也许您可以帮助我找到它,我将编辑此内容以消除故障。该函数接受类似于eth0的接口名称,并返回该接口使用的网关的IP地址。
char* GetGatewayForInterface(const char* interface) {
  char* gateway = NULL;

  FILE* fp = popen("netstat -rn", "r");
  char line[256]={0x0};

  while(fgets(line, sizeof(line), fp) != NULL)
  {    
    /*
     * Get destination.
     */
    char* destination;
    destination = strndup(line, 15);

    /*
     * Extract iface to compare with the requested one
     * todo: fix for iface names longer than eth0, eth1 etc
     */
    char* iface;
    iface = strndup(line + 73, 4);


    // Find line with the gateway
    if(strcmp("0.0.0.0        ", destination) == 0 && strcmp(iface, interface) == 0) {
        // Extract gateway
        gateway = strndup(line + 16, 15);
    }

    free(destination);
    free(iface);
  }

  pclose(fp);
  return gateway;
}

这个函数的问题在于,如果我将pclose保留在其中,它会导致内存损坏崩溃。但是,如果我删除pclose调用,它可以工作(但那不是一个好的解决方案,因为流将保持打开状态.. 嘿嘿)。所以,如果有人能发现错误,我将使用正确的版本编辑该函数。我不是C专家,对所有的内存操作都感到有些困惑 ;)


1
你所发布的代码中没有任何可能导致内存损坏崩溃的问题。我通过使用valgrind运行代码进行了确认。 - indiv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接