小练习

来源:互联网 发布:网络教育统考报名网 编辑:程序博客网 时间:2024/04/20 20:58

有次用到了IP地址int与str的转换,不想用socket的库函数,发现网上很多实现都挺啰嗦的,自己实现了一个,记录下,大小端序可以根据实际使用进一步做转换。

/* ip 字符串合法性由调用者保证 */unsigned int ip_str2int(const char* ip){    unsigned int re = 0;    unsigned char tmp = 0;    while (1) {        if (*ip != '\0' && *ip != '.') {            tmp = tmp * 10 + *ip - '0';        } else {            re = (re << 8) + tmp;            if (*ip == '\0')                break;            tmp = 0;        }        ip++;    }    return re;}/* str长度合法性由调用者保证 */void ip_int2str(const unsigned int ip, char str[]){    unsigned char *val = (unsigned char *)&ip;    sprintf(str, "%u.%u.%u.%u", val[3], val[2], val[1], val[0]);}
1 0