Linux下获取网卡信息

// all.h
// wenxy created on 2005/04/12,AM
// All copyright reserved.


#ifndef _ALL_H
#define _ALL_H

// ANSC C/C++
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <assert.h>
#include <errno.h>

// linux
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>  // socket
#include <arpa/inet.h>
#include <sys/times.h>  // time
#include <sys/select.h> 
#include <sys/ioctl.h>
#include <net/if.h>
//#include <net/if_arp.h>

#include <sys/wait.h>
#include <sys/stat.h>


// micro
//#define OutErrStr(info) (printf("Error : %s/n", info))

//#define OutErrInt(info) (printf("Error : %d/n", info))
#define BUFF_SIZE   (1024 * 1)
#define MAX_NIC    16 

#endif

// --------------------------------------------------------------------------------------------------

// main.c

#include "all.h"

// function
static bool GetNICInfo(void *pBuff, ...);

// global variable
int g_nSocket = 0;
char chBuff[BUFF_SIZE];


int main(int argc, char *argv[])
{
 printf("Run .../n");
 if ( ! GetNICInfo(NULL) )
 {
  printf("Error : call GetNICInfo() function failed/n");
  printf("-----------------------------------/n/n");
 }

 return 0;
}


// NIC attribute
static bool GetNICInfo(void *pBuff, ...)
{
 if ( -1 == (g_nSocket = socket(AF_INET, SOCK_DGRAM, 0)) )
 {
  printf("Error: create socket failed/n");
  printf("-----------------------------------/n/n");
  return false;
 }

 struct ifconf ifc;
 struct ifreq buff[MAX_NIC];
 unsigned int uNICCount = 0;
 struct sockaddr_in *pAddr;
 memset( &ifc, 0, sizeof(struct ifconf) );
 memset( &buff, 0, sizeof(struct ifreq) );
 //  control device which name is NIC
 if ( ! ioctl (g_nSocket, SIOCGIFCONF, (char *) &ifc) )
 {
  uNICCount = ifc.ifc_len / sizeof(struct ifreq);
  printf("NIC total is : %d/n", uNICCount);
  while ( uNICCount -- > 0 )
  {
   if ( ! (ioctl (g_nSocket, SIOCGIFADDR, (char *) &buff[uNICCount]) ) )
   {
    pAddr = (struct sockaddr_in *) (&buff[uNICCount].ifr_addr);
    printf("IP : %s/n", inet_ntoa( (pAddr->sin_addr ) ));
   }
   else
   {
    printf("Error :  read NIC information failed/n");
    printf("-----------------------------------/n/n");
   }
  }

 }

 if (g_nSocket)
 {
  close(g_nSocket);
 }
 return true;
}

// --------------------------------------------------------------------------------------------------------

# makefile

bin = nic_info
objets = main.o

rubbish = $(objets) $(bin)


$(bin) : main.o
 g++ -g -o $(bin) main.o

main.o : main.c all.h
 g++ -g -c main.c


.PHONY : clean
clean :
 -rm $(rubbish)
 


# end makefile
 
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值