Menu Home

linux c获取系统网卡信息

OS:ubuntu 12.04

int getNetCardCount()
{
    int nCount = 0;
    FILE *file = fopen("/proc/net/dev", "r");
    if(!file)
    {   
        debug("Open /proc/net/dev failed by %s !\n", strerror(errno));
        return nCount;
    }   

    char szLine[512];
    fgets(szLine, sizeof(szLine), file);
    fgets(szLine, sizeof(szLine), file);

    while(fgets(szLine, sizeof(szLine), file))
    {   
        char szName[128] = {0};
        sscanf(szLine, "%s", szName);
        int nLen = strlen(szName);
        if(nLen <= 0)
            continue;
        if(szName[nLen - 1] == ':')
            szName[nLen - 1] = 0;
        if(strcmp(szName, "lo") == 0)
            continue;
        nCount++;
    }   

    fclose(file);
    file = NULL;
    return nCount;
}

void dispNetInfo(const char *szDevName, struct netCardInfo *netCardInfo)
{
    int s = socket(AF_INET, SOCK_DGRAM, 0);
    if(s < 0)
    {
        debug("Create socket failed by %s!\n", strerror(errno));
        return;
    }
    struct ifreq ifr;
    unsigned char mac[6];
    unsigned long nIP, nNetmask, nBroadIP;

    strcpy(netCardInfo->devName, szDevName);
    printf("%s\n", szDevName);

    strcpy(ifr.ifr_name, szDevName);
    if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
    {
        return;
    }
    memcpy(netCardInfo->mac, ifr.ifr_hwaddr.sa_data, sizeof(mac));
    //fprintf(stderr, "\tMAC:%02x-%02x-%02x-%02x-%02x-%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    strcpy(ifr.ifr_name, szDevName);
    if(ioctl(s, SIOCGIFADDR, &ifr) < 0)
        nIP = 0;
    else
        nIP = *(unsigned long*)&ifr.ifr_broadaddr.sa_data[2];

    strcpy(netCardInfo->IP,  inet_ntoa(*(struct in_addr*)&nIP));

    //fprintf(stderr, "\tIP:%s\n", inet_ntoa(*(struct in_addr*)&nIP));

    strcpy(ifr.ifr_name, szDevName);
    if(ioctl(s, SIOCGIFBRDADDR, &ifr) < 0)
        nBroadIP = 0;
    else
        nBroadIP = *(unsigned long*)&ifr.ifr_broadaddr.sa_data[2];
    strcpy(netCardInfo->broadIp, inet_ntoa(*(struct in_addr*)&nBroadIP));
    //fprintf(stderr, "\tBroadIP:%s\n", inet_ntoa(*(struct in_addr*)&nBroadIP));

   strcpy(ifr.ifr_name, szDevName);
    if(ioctl(s, SIOCGIFNETMASK, &ifr) < 0)
        nNetmask = 0;
    else
        nNetmask = *(unsigned long*)&ifr.ifr_netmask.sa_data[2];
    strcpy(netCardInfo->netMask, inet_ntoa(*(struct in_addr*)&nNetmask));
    //fprintf(stderr, "\tNetmask:%s\n", inet_ntoa(*(struct in_addr*)&nNetmask));

    strcpy(ifr.ifr_name, szDevName);
    if(ioctl(s, SIOCGIFMTU, &ifr) < 0)
        netCardInfo->mtu = 0;
    else
        netCardInfo->mtu = ifr.ifr_mtu;
        //fprintf(stderr, "\tMTU:%d", ifr.ifr_mtu);

    close(s);
}

void dispActiveAdap(struct netInfo *netInfo)
{
    int fd;
    int count;
    struct ifconf ifc;
    struct ifreq ifr[512];

    if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        debug("socket error by %s\n", strerror(errno));
        return;
    }
    bzero(&ifc, sizeof(ifc));
    bzero(ifr, sizeof(ifr));
    ifc.ifc_len = sizeof(ifr);
    ifc.ifc_req = ifr;
    if(ioctl(fd, SIOCGIFCONF, &ifc) < 0)
    {
        debug("ioctl error by %s\n", strerror(errno));
        return;
    }
    count = ifc.ifc_len / sizeof(struct ifreq);
    int i;
    for(i = 0; i < count; i++)
    {
        struct ifreq *req = &ifr[i];
        if ((strcmp(req->ifr_name, "lo") != 0))
        {
            dispNetInfo(req->ifr_name, &(netInfo->cardInfo[i]));
        }
    }
    close(fd);
    return ;
}

void getDNS(struct netInfo *netInfo)
{
    int i;
    if(res_init() < 0)
    {
        debug("res_init error by %s\n", strerror(errno));
        return;
    }
    for(i = 0; i < _res.nscount; i++)
    {
        struct sockaddr *server = (struct sockaddr*)&_res.nsaddr_list[i];
        strcpy(netInfo->dns[i], inet_ntoa(*(struct in_addr*)&(server->sa_data[2])));
        //fprintf(stderr, "DNS%d:%s\n",i+1, inet_ntoa(*(struct in_addr*)&(server->sa_data[2])));
    }
}

14 replies

  1. hey there and thanks on your information – I’ve certainly picked up anything new from proper here. I did however expertise some technical issues the usage of this web site, since I skilled to reload the website many times prior to I may get it to load correctly. I had been thinking about in case your hosting is OK? No longer that I am complaining, however sluggish loading circumstances instances will often affect your placement in google and could damage your high quality ranking if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I am adding this RSS to my e-mail and could glance out for much more of your respective fascinating content. Make sure you replace this once more very soon..

  2. I and also my guys have been reading the great tricks on your web blog and so suddenly got an awful feeling I never thanked the web blog owner for those tips. All the guys were definitely for this reason very interested to read through them and now have in reality been having fun with those things. Appreciate your really being very accommodating as well as for picking out this kind of good subject areas millions of individuals are really needing to be aware of. My personal sincere apologies for not expressing gratitude to you sooner.

  3. I must show thanks to the writer for bailing me out of this type of trouble. As a result of browsing through the search engines and seeing ways that were not pleasant, I thought my life was done. Existing devoid of the strategies to the issues you’ve sorted out by means of your entire article is a crucial case, and ones which may have negatively damaged my career if I had not discovered your web site. That ability and kindness in taking care of all the pieces was excellent. I don’t know what I would have done if I had not discovered such a step like this. I can also at this moment look forward to my future. Thank you so much for your high quality and effective guide. I won’t be reluctant to refer your web blog to anybody who will need support about this area.

  4. Thank you so much for giving everyone a very nice possiblity to read critical reviews from here. It’s usually very pleasurable plus stuffed with a great time for me personally and my office mates to search your website no less than 3 times weekly to find out the latest stuff you have got. And definitely, we are at all times fulfilled considering the mind-boggling knowledge you give. Selected 2 tips on this page are particularly the most efficient we have all had.

  5. I must show appreciation to the writer just for bailing me out of such a setting. Just after browsing throughout the world-wide-web and obtaining ways which were not beneficial, I assumed my entire life was gone. Living without the approaches to the problems you have fixed by way of your entire site is a serious case, as well as the kind that would have adversely damaged my career if I had not encountered the website. Your main expertise and kindness in handling almost everything was vital. I am not sure what I would’ve done if I hadn’t come upon such a stuff like this. I can also at this moment relish my future. Thanks a lot very much for the professional and amazing guide. I will not think twice to recommend the website to any person who should receive guide on this matter.

  6. My wife and i have been very fulfilled Louis managed to finish off his reports through your ideas he received when using the web page. It is now and again perplexing to simply choose to be giving away secrets and techniques that other folks have been selling. Therefore we fully grasp we now have the website owner to give thanks to for that. The main explanations you’ve made, the simple web site navigation, the friendships you can make it easier to instill – it is all astounding, and it is letting our son in addition to our family reckon that the concept is exciting, and that is exceptionally fundamental. Thanks for all the pieces!

  7. I simply desired to appreciate you again. I do not know what I could possibly have created without the actual smart ideas contributed by you on such subject matter. It seemed to be the depressing difficulty in my position, however , being able to see your specialised tactic you managed that took me to leap for delight. Now i’m thankful for your assistance and sincerely hope you really know what a powerful job that you’re carrying out instructing many people through your blog post. More than likely you have never met all of us.

  8. Thanks a lot for providing individuals with remarkably terrific chance to read articles and blog posts from this blog. It is often very useful and also stuffed with fun for me and my office fellow workers to search the blog more than thrice per week to find out the latest items you will have. And of course, I’m also certainly happy for the mind-boggling solutions you serve. Selected 2 facts in this posting are surely the most effective I’ve had.

  9. I just wanted to develop a brief word in order to say thanks to you for all of the wonderful ideas you are writing at this website. My considerable internet look up has now been rewarded with wonderful ideas to write about with my guests. I ‘d say that most of us visitors actually are undeniably blessed to be in a useful network with many special individuals with insightful tips and hints. I feel very much privileged to have encountered the website page and look forward to so many more fun moments reading here. Thank you once again for all the details.

  10. I have to show some thanks to you just for bailing me out of this particular trouble. Right after looking throughout the the web and finding tricks that were not helpful, I believed my life was well over. Living minus the strategies to the difficulties you’ve sorted out as a result of your post is a critical case, as well as ones which could have badly affected my entire career if I had not noticed your website. Your actual ability and kindness in touching all the stuff was excellent. I am not sure what I would have done if I had not encountered such a point like this. I can at this moment relish my future. Thanks for your time very much for your skilled and result oriented guide. I won’t think twice to recommend your web blog to anyone who should receive recommendations on this situation.

  11. Thanks a lot for providing individuals with remarkably remarkable chance to check tips from this blog. It’s always so great plus jam-packed with fun for me personally and my office fellow workers to visit your site minimum 3 times per week to find out the fresh tips you will have. Of course, I am just actually impressed considering the wonderful knowledge you give. Some 2 facts in this post are in fact the simplest we have all ever had.

  12. Thanks so much for giving everyone a very spectacular possiblity to read from this web site. It is usually so good and also jam-packed with a great time for me personally and my office friends to search your web site minimum thrice a week to read the newest guides you have. Of course, we are always fascinated with the very good inspiring ideas you serve. Certain 3 areas on this page are absolutely the very best we have had.

  13. Thanks a lot for giving everyone an exceptionally remarkable chance to read critical reviews from this web site. It is usually very excellent and as well , jam-packed with a lot of fun for me personally and my office fellow workers to search your blog really three times weekly to study the new guidance you have. And lastly, I’m so always satisfied with the mind-boggling inspiring ideas you give. Selected 2 tips in this post are easily the finest we have had.

  14. I want to show my thanks to you for rescuing me from such a incident. Right after searching throughout the online world and finding suggestions which are not productive, I assumed my life was gone. Being alive without the solutions to the problems you’ve solved through the post is a critical case, and ones which could have badly affected my career if I had not discovered your website. Your own personal ability and kindness in maneuvering all things was valuable. I am not sure what I would’ve done if I hadn’t come across such a step like this. I can now relish my future. Thanks a lot very much for this high quality and sensible help. I will not think twice to refer your blog post to any person who requires guidelines about this matter.

Leave a Reply

Your email address will not be published.