现在的位置: 首页 > 综合 > 正文

tcp/ip中的 ip字符串转整数函数 inet_aton 源代码

2013年11月26日 ⁄ 综合 ⁄ 共 695字 ⁄ 字号 评论关闭
// ip地址结构体
struct in_addr
{
	unsigned int s_addr; // network byte order( big-endian)
};

// inet_aton将 点分十进制串cp 转换为一个网络字节顺序的32位整数 IP地址
// 例如将串cp "192.168.33.123 "
// 转为 1100 0000   1010 1000    0010 0001     0111 1011 
// 成功返回1,出错返回0
// 转换成功,结果保存在结构体指针ap中
int inet_aton(const char *cp, struct in_addr *ap)
{
    int dots = 0;
    register u_long acc = 0, addr = 0;
	
    do {

			register char cc = *cp;
		
			switch (cc) 
			{
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					acc = acc * 10 + (cc - '0');
					break;
					
				case '.':
					if (++dots > 3)
					{
						return 0;
					}
					// Fall through
					
				case '/0':
					if (acc > 255) 
					{
						return 0;
					}
					addr = addr << 8 | acc; // 这句是精华,每次将当前值左移八位加上后面的值
					acc = 0;
					break;
					
				default:
					return 0;
			}

    } while (*cp++) ;
	
    // Normalize the address 
    if (dots < 3)
	{
		addr <<= 8 * (3 - dots) ;
    }
	
    //Store it if requested 
    if (ap) 
	{
		ap->s_addr = htonl(addr);
    }
	
    return 1;    
}

抱歉!评论已关闭.