ipv4地址转换

本文详细介绍了IPv4地址从整数到字符串的解析过程及从字符串到整数的转换方法,包括具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ipv4地址解析


/* ipv4 无符号整数转化为字符串 */
void ipv4_to_str(char *addr_str, unsigned int ipv4_addr)
{
	/* ipv4 地址32位, 输出格式:A.B.C.D */
	sprintf(addr_str, "%d.%d.%d.%d",
				(ipv4_addr >> 24) & 0xff,
				(ipv4_addr >> 16) & 0xff,
				(ipv4_addr >> 8)& 0xff,
				(ipv4_addr) & 0xff);
}


/* ipv4 地址 字符串转换为无符号整形 */
int ipv4_to_i(char *addr_str, unsigned int *ipv4_addr_ptr)
{
	/********************************************************************/
	/* 功能:解析ipv4地址字符串,转换为无符号整形            */
	/* ipv4地址 32位     									 */
	/* 输入:A.B.C.D 字符串                                  */
	/* 输出:返回解析成功或失败;无符号整形表示的ipv4地址     */
	/********************************************************************/
	
	unsigned int addr = 0;
	int addr_int_component; // 每个域(8位)的整形表示
	int current_addr_comp;  // 当前所在域
	int current_comp_str_pos; // 当前字符串域中第一个字符偏移位置
	int str_pos; //字符位置
	
	current_addr_comp = 0;
	current_comp_str_pos = 0;
	
	for (str_pos = 0;  ; str_pos++)
	{
		// 可能提前结束
		if ('.' == addr_str[str_pos] || 0 == addr_str[str_pos])
		{
			// 当前域结束,转换为整形,并检查范围是否合法
			addr_int_component = atoi(addr_str + current_comp_str_pos);
			if (addr_int_component > 255 || addr_int_component < 0)
			{
				return 0;
			}
			
			// 把当前域加入到地址中
			addr = (addr & (~(255 << (24 - current_addr_comp * 8)))) | 
										(addr_int_component << (24 - current_addr_comp * 8));
			
			// 移动到下一个域, 并坚持是否最后一个域已解析完成
			current_addr_comp++;
			if (4 == current_addr_comp)
			{
				// 解析完成
				break;
			}
			
			// 移动到字符串地址下一个域中第一个字符,即'.'的右侧
			current_comp_str_pos = str_pos + 1;
		}
		else
		{
			// 字符串中字符不是点或字符串结束标识,就是数字或'/'
			if (!isdigit((unsigned char)addr_str[str_pos]) && (addr_str[str_pos] != '/'))
			{
				return 0;
			}
		}
		
		// 已处理字符串结束标识,退出
		if (0 == addr_str[str_pos])
			{
				break;
			}
	}
	*ipv4_addr_ptr = addr;
	
	return 1;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值