获得本地IP的三种方法

  • 方法1,windows平台能拿到所有网卡IP,linux只能获得 "127.0.0.1"
int m_get_localIP(char** ipList, int num)
{
	int i = 0;
	const char* ip = NULL;
	struct hostent* h = NULL;
	char hostname[128] = {0};
	
	if(gethostname(hostname, sizeof(hostname)) != 0 || (h = gethostbyname(hostname)) == NULL)
	{
		return -1;
	}
	//get the ip address if it has multiple
	for(i = 0;i < num && h->h_addr_list[i];i++)
	{
		ip = inet_ntoa(*(struct in_addr*)h->h_addr_list[i]);
		if(strcmp(ip, "127.0.0.1") != 0)
		{
			strcpy(ipList[i++], ip);
		}
	}
	return i;
}
  • 方法2,linux平台可以拿到所有网卡IP,windows没有定义SIOCGIFCONF 和SIOCGIFADDR
int m_get_localIP(char** ipList, int num)
{
	int fd = -1;
	int i = -1, ret = 0;
	const char* ip = NULL;
	struct ifconf ifc = {0}; ///if.h
	struct ifreq* buf = NULL;

	if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		return -1;
	}
	ifc.ifc_len = num * sizeof(struct ifreq);
	buf = (struct ifreq*)malloc(ifc.ifc_len);
	ifc.ifc_buf = (caddr_t)buf;
	if(ioctl(fd, SIOCGIFCONF, (char*)&ifc) == 0) //ioctl.h
	{
		i = 0;
		ret = ifc.ifc_len / sizeof(struct ifreq);
		while(ret-- > 0 && i < num)
		{
			if((ioctl(fd, SIOCGIFADDR, (char*)&buf[ret])) == 0)
			{
				ip = (inet_ntoa(((struct sockaddr_in*)(&buf[ret].ifr_addr))->sin_addr));//types
				if(strcmp(ip, "127.0.0.1") != 0)
				{
					strcpy(ipList[i++], ip);
				}
			}
		}
	}
	close(fd);
	free(buf);
	return i;
}
  • 方法三,各平台通用,但是只能获得系统分配的网卡IP,不能拿到所有网卡IP
 
int m_get_localIP(char** ipList, int num)
{
    int fd = -1;  
    int i = -1, ret = 0;  
    const char* ip = NULL;  
    struct sockaddr_in addr = {0};  
  
    if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)  
    {  
        return -1;  
    }  
    memset(&addr, 0, sizeof(addr));  
    addr.sin_family = AF_INET;  
    addr.sin_addr.s_addr = inet_addr("8.8.8.8");  
    addr.sin_port = htons(80);  
    ret = sizeof(addr);  
    ret = connect(fd, (struct sockaddr*)&addr, ret);  
    i = 0;  
    ret = sizeof(addr);  
    if(getsockname(fd, (struct sockaddr*)&addr, (int*)&ret) == 0)  
    {  
        fprintf(stdout, "ip=%s\n", inet_ntoa(addr.sin_addr));  
    }  
    close(fd);  
    return i;  
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值