获取主机基本信息

获取当前主机名字,时间信息,mac地址,ip 地址

#include <stdio.h>
#include <pwd.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <net/if.h>		/* for ifconf */
#include <linux/sockios.h>	/* for net status mask */
#include <netinet/in.h>		/* for sockaddr_in */
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>

char account_name[32];
char mac_address[64] = {0};
char ip[64]  = {0};
char local_info[512] = {0};
char local_time[32] = {0};

int get_local_time() 
{

    time_t curTime = time(NULL);
    struct tm *test_time =localtime(&curTime);
    snprintf(local_time, sizeof(local_time), "time=%04d-%02d-%02d %02d:%02d:%02d",
            test_time->tm_year + 1900,
            test_time->tm_mon + 1,
            test_time->tm_mday,
            test_time->tm_hour,
            test_time->tm_min,
            test_time->tm_sec);
	return 0;

}
int get_computer_account()
{
	// 获取用户名
	struct passwd *user_info = getpwuid(getuid());
	
	if(user_info->pw_name  == NULL)
		return -1;

	//memcpy(account_name,user_info->pw_name,strlen(user_info->pw_name));
	snprintf(account_name,sizeof(account_name),"account = %s",user_info->pw_name);
	printf("login account : %s \n",account_name);
	return 0;
}


int get_mac(char *network_name)
{
    int sockfd;
    struct ifreq req;
    char buf[32] = {0};

    int i = 0;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("fail to create socket ..!");
        exit(1);
    }

    printf("set network_name = %s \n", network_name);
    strcpy(req.ifr_ifrn.ifrn_name, network_name);
    if (ioctl(sockfd, SIOCGIFHWADDR, &req) < 0) {
        perror("fail to ioctl ");
        close(sockfd);
        exit(1);
    }
    memcpy(buf, req.ifr_ifru.ifru_hwaddr.sa_data, 6);
   snprintf(mac_address, sizeof(mac_address), "mac=%02X:%02X:%02X:%02X:%02X:%02X",buf[0]& 0xff,buf[1]& 0xff,buf[2]& 0xff,buf[3]& 0xff,buf[4]& 0xff,buf[5]& 0xff);
// snprintf(mac_address, sizeof(mac_address), "MAC:%2X:%2X:%2X:%2X:%2X:%2X",buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]);

   close(sockfd);
 
    return 0;
}

int get_network_infomation()
{
	struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;
 
    getifaddrs(&ifAddrStruct);
 
      for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
	{
        if (!ifa->ifa_addr)
	 {
            continue;
        }


        if (ifa->ifa_addr->sa_family == AF_INET ) // check it is IP4
	{
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); 
            if(strcmp(addressBuffer,"127.0.0.1") == 0)
                                continue;
                          
       printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
       snprintf(ip, sizeof(ip),"ip=%s",addressBuffer);
       get_mac(ifa->ifa_name);
       break;   //只获取第一个网卡的mac 和ip
    }

}
	if (ifAddrStruct!=NULL)
	   freeifaddrs(ifAddrStruct);
	 
    return 0;

}

int get_local_information()
{
get_computer_account();
get_local_time();
get_network_infomation();
snprintf(local_info, sizeof(local_info),"%s %s %s %s",account_name ,local_time, mac_address,ip);
}

int main(int argc, char * argv[])
{
get_local_information();
printf("%s \n",local_info);
return 0;

}

输出结果:

login account : account = uos 
wlp2s0 IP Address 10.20.6.126
set network_name = wlp2s0 
account = uos time=2022-10-17 16:17:03 mac=74:12:B3:58:AE:E1 ip=10.20.6.126 

性能优化减少中间临时变量使用,利用好返回值长度,对数据进行拼接

使用localtime_r 替代localtime 解决线程竞争问题

修改后的代码

#include <stdio.h>
#include <pwd.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <net/if.h>		   /* for ifconf */
#include <linux/sockios.h> /* for net status mask */
#include <netinet/in.h>	   /* for sockaddr_in */
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>


static char s_ip[64] = {0};
static char s_hostname[128] = {0};
static char s_local_time[32] = {0};
static char s_mac_address[64] = {0};


int get_local_time()
{

	time_t cur_time = time(NULL);
	struct tm local_time;
	struct tm *test_time = localtime_r(&cur_time,&local_time);
	snprintf(s_local_time, sizeof(s_local_time), "time=%04d-%02d-%02d %02d:%02d:%02d",
			 test_time->tm_year + 1900,
			 test_time->tm_mon + 1,
			 test_time->tm_mday,
			 test_time->tm_hour,
			 test_time->tm_min,
			 test_time->tm_sec);
	return 0;
}

int get_hostname()
{
	int r = 0;
	int len = 0;
	FILE *fp = NULL;
	fp = fopen("/etc/hostname", "r"); //将命令hostname 同过管道读到fp
	len = snprintf(s_hostname, sizeof(s_hostname), "hostname=");
	if (fp == NULL)
	{
		snprintf(&s_hostname[len], sizeof(s_hostname)-len, "NULL");
		return -1;
	}

	r = fread(&s_hostname[len], 1, sizeof(s_hostname), fp);                 //将fp的数据流读到buff中
	if (r <= 0)
	{
		snprintf(&s_hostname[len], sizeof(s_hostname)-len, "NULL");
		fclose(fp);
		return -1;
	}
	
	s_hostname[len+r-1] = '\0'; // 将\n替换为\0
	fclose(fp);
	return 0;
}

int get_mac(char *network_name)
{
	int i = 0;
	int len = 0;
	int sockfd;
	struct ifreq req;
	char buf[6] = {0};

	len = snprintf(s_mac_address, sizeof(s_mac_address), "mac=");
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		snprintf(&s_mac_address[len], sizeof(s_mac_address)-len, "NULL");
		perror("fail to create socket ..!");
		return -1;
	}

	strcpy(req.ifr_ifrn.ifrn_name, network_name);
	if (ioctl(sockfd, SIOCGIFHWADDR, &req) < 0)
	{   
		snprintf(&s_mac_address[len], sizeof(s_mac_address)-len, "NULL");
		perror("fail to ioctl ");
		close(sockfd);
		return -1;
	}
	memcpy(buf, req.ifr_ifru.ifru_hwaddr.sa_data, 6);
	snprintf(&s_mac_address[len], sizeof(s_mac_address)-len, "%02X:%02X:%02X:%02X:%02X:%02X", buf[0] & 0xff, buf[1] & 0xff, buf[2] & 0xff, buf[3] & 0xff, buf[4] & 0xff, buf[5] & 0xff);
	close(sockfd);

	return 0;
}

int get_network_infomation()
{
	int len = 0;
	struct ifaddrs *ifAddrStruct = NULL;
	struct ifaddrs *ifa = NULL;
	void *tmpAddrPtr = NULL;

	getifaddrs(&ifAddrStruct);

	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
	{
	
		if (!ifa->ifa_addr)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET) // check it is IP4
		{
			// is a valid IP4 Address
			tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
  
  printf("tmpAddrPtr = %x \n", *(int*)tmpAddrPtr);
     if ((*(int*)tmpAddrPtr == 0x7f00001) || (*(int*)tmpAddrPtr == 0x100007f))
				continue;
        
			len = snprintf(s_ip, sizeof(s_ip), "ip=");
			inet_ntop(AF_INET, tmpAddrPtr, &s_ip[len], INET_ADDRSTRLEN);
			get_mac(ifa->ifa_name);
			break; //只获取第一个网卡的mac 和 ip
		}
	}
	if (ifAddrStruct != NULL)
		freeifaddrs(ifAddrStruct);

	return 0;
}


int main(char *argc, char *argv[])
{

    get_hostname();
	get_local_time();
	get_network_infomation();
	/* write it to disk */
	printf("%s %s %s %s \n", s_local_time, s_hostname, s_mac_address, s_ip);


}

输出结果

tmpAddrPtr = 100007f 
tmpAddrPtr = 7e06140a 

time=2022-10-26 14:43:18 hostname=test_pc mac=74:12:B3:58:AE:E1 ip=10.20.6.126 

准确分配数据,避免空间浪费

(gdb) call sizeof("mac=74:12:B3:58:AE:E1")
$5 = 22
(gdb) call sizeof("mac=74:12:B3:58:AE:E1")
$6 = 22
s_mac_addr[24]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值