Linux C++获取本地系统名称和ip地址

使用封装的这个函数获取系统的名称和ip

#include <iostream> /* cout */
#include <unistd.h>/* gethostname */
#include <netdb.h> /* struct hostent */
#include <arpa/inet.h> /* inet_ntop */
 
bool GetHostInfo(std::string& hostName, std::string& Ip) {
	char name[256];
	gethostname(name, sizeof(name));
	hostName = name;
	
	struct hostent* host = gethostbyname(name);
	char ipStr[32];
	const char* ret = inet_ntop(host->h_addrtype, host->h_addr_list[0], ipStr, sizeof(ipStr));
	if (NULL==ret) {
		std::cout << "hostname transform to ip failed";
		return false;
	}
	Ip = ipStr;
	return true;
}

进行测试:

//以下测试
int main(int argc, char *argv[]) {
	std::string hostName;
	std::string Ip;
	
	bool ret = GetHostInfo(hostName, Ip);
	if (true == ret) {
		std::cout << "hostname: " << hostName << std::endl;
		std::cout << "Ip: " << Ip << std::endl;
	}
	return 0;
}

输出结果:略

转载自:https://blog.csdn.net/lmb1612977696/article/details/78900596

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值