C/C++获取系统IP地址

这篇博客介绍了一个C语言函数,用于从/etc/hosts文件获取本地主机的IP地址。函数通过gethostname和gethostbyname系统调用实现,然后使用inet_ntop将IP地址转换为字符串形式。在使用该函数前,需要确保hosts文件中有正确的主机名-IP对应关系。
摘要由CSDN通过智能技术生成

说明:使用该封装的函数,必须保证/etc/hosts下有主机名和IP的对应关系,否则会失败。

封装

#include <unistd.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

int get_localhost_ip(char *buff)
{
	char hostname[32];
	struct hostent *hptr;
	char buff_tmp[32];
	const char *ptr;

	if(buff==0)
	{
		printf("buff==0\n");
		return -1;
	}

	buff[0]=0;
	
	if(gethostname(hostname,sizeof(hostname)) == -1)
	{
		perror("gethostname");
		return -1;
	}

	if((hptr = gethostbyname(hostname)) == NULL)
	{
		perror("gethostbyname");
		return -1;
	}

	ptr=inet_ntop(hptr->h_addrtype, hptr->h_addr, buff_tmp, sizeof(buff_tmp));
	if(ptr==NULL)
	{
		perror("inet_ntop");
		return -1;
	}

	strcpy(buff,buff_tmp);

	return 1;
}

使用

void main()
{
	char ip[32];

	if(get_localhost_ip(ip) < 0)
	{
		printf("get_localhost_ip failed\n");
		return;
	}

	printf("ip = %s\n",ip);
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

历史五千年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值