Linux下获取网卡信息
// all.h// wenxy created on 2005/04/12,AM// All copyright reserved.#ifndef _ALL_H#define _ALL_H// ANSC C/C++#include #include #include #include #include // linux#include #include #include #include #in
// 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)