首页 > 代码库 > 获取IPRouter信息,出口默认网关。

获取IPRouter信息,出口默认网关。

#define ROUTE_FILE_NAME "/proc/net/route"

/*

Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT

wan1 00000000 5692550A 0003 0 0 0 00000000 0 0 0

wan1 0000000A 00000000 0001 0 0 0 000000FF 0 0 0

br0 0022A8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0

×/

int getGatewayByDevName(const char *devName, char *outText){
    
    outText[0] = \0;
    
    char buffer[BIG_MAX_FIELD_LEN];
    char destination[NORMAL_FIELD_LEN];
    unsigned long gateway;
    
    FILE* f = fopen(ROUTE_FILE_NAME, "r");
    
    if(!f){
        return 1;
    }
    int devNamelen = strlen(devName);
    while(fgets(buffer, sizeof(buffer)-1, f)){
        if(!strncmp(buffer, devName, devNamelen)){
            sscanf(buffer, "%*s%s%lX", destination, &gateway);
            if(!strncmp(destination, "00000000", 8)){
                if (gateway != 0) {
                    sprintf(outText, "%s", inet_ntoa(*(struct in_addr*)&gateway));
                    break;
                }
            }
        }
    }
    
    fclose(f);
    
    return 0;
}

具体的头文件要包含

inet_ntoa结构体所在的头文件

获取IPRouter信息,出口默认网关。