如何通过C++编程实现获取Linux系统下的一些系统信息

如何通过C++编程实现获取Linux系统下的一些系统信息,第1张

C语言有一个system函数(在头中,C++则为头),可以用来调用终端命令。原型如下: int system(const char *cmdline /* 命令字符串 */)例如,Linux系统中,调用system("ls -la")将输出当前目录下的所有文件详细信息。

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <net/if.h>

#include <netdb.h>

#include <arpa/inet.h>

#include <sys/ioctl.h>

//获取地址

//返回IP地址字符串

int getlocalip(char* outip)

{

int i=0

int sockfd

struct ifconf ifconf

char buf = (char)malloc(512)

struct ifreq *ifreq

char* ip

//初始化ifconf

ifconf.ifc_len = 512

ifconf.ifc_buf = buf

if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)

{

return -1

}

ioctl(sockfd, SIOCGIFCONF, &ifconf) //获取所有接口信息

close(sockfd)

//接下来一个一个的获取IP地址

ifreq = (struct ifreq*)buf

i = ifconf.ifc_len/sizeof(struct ifreq)

char *pos = outip

int count

for(count = 0 (count < 5 && i > 0) i--)

{

ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr)

if(strncmp(ip,"127.0.0.1", 3)==0) //排除127.x.x.x,继续下一个

{

ifreq++

continue

}else

{

printf("%s\n", ip)

strcpy(pos,ip)

int len = strlen(ip)

pos = '\t'

pos += len+1

count ++

ifreq++

}

}

free(buf)

return 0

}

//——————————-函数的调用方式————————————-

int main(int argc, char** argv)

{

char ip = {'*'}

if ( getlocalip( ip ) == 0 )

{

printf("本机IP地址是: %s\n", ip )

}

else

{

printf("无法获取本机IP地址 ")

}

return 0

}

可以使用getuid()获取用户的ID号,然后通过getpwuid函数通过用户的uid查找用户的passwd数据来获取系统登录的用户名。

#include

#include

#include

int main(void)

{

struct passwd *pwd

pwd = getpwuid(getuid())

printf("当前登陆的用户名为:%s\n", pwd->pw_name)

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/yw/8494344.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-17
下一篇 2023-04-17

发表评论

登录后才能评论

评论列表(0条)

保存