ipv4地址向int型转换,int型数据向ipv4转换。

  将一个ip地址格式的字符串转换为一个int型(4字节32位)的数据。例如 char *p = "192.168.001.001"; 

  函数实现如下:

int ipv4_to_int(char *ip)
{
    int tmp = 0;
    char ip1, ip2, ip3, ip4;

    ip1 = atoi(ip);
    ip = strchr(ip, '.');
    if(!ip)
        return -1;
    ip2 = atoi(++ip);
    ip = strchr(ip, '.');
    if(!ip)
        return -1;
    ip3 = atoi(++ip);
    ip = strchr(ip, '.');
    if(!ip)
        return -1;
    ip4 = atoi(++ip);

    tmp |= ip4 & 0xff;
    tmp = (tmp << 8) | (ip3 & 0xff);
    tmp = (tmp << 8) | (ip2 & 0xff);
    tmp = (tmp << 8) | (ip1 & 0xff);

    return tmp;
}

  打印tmp值为0101a8c0。其中c0在低地址(主机小端结构)。

  将一个int型ip地址转换为ipv4的结构,使用如下的函数实现。

void int_to_ipv4(int tmp, char *ip)
{
    unsigned short ip1, ip2, ip3, ip4;
    ip1 = tmp & 0xff;
    ip2 = (tmp >> 8) & 0xff;
    ip3 = (tmp >> 16) & 0xff;
    ip4 = (tmp >> 24) & 0xff;
    sprintf(ip, "%03d.%03d.%03d.%03d", (int)ip1, (int)ip2, (int)ip3, (int)ip4);
}

  将上个数据信息转换成ipv4后,结果为192.168.001.001。

  通过判断一个字符串中是否有三个点来判断该字符串是否为一个ipv4字符串,同样也可以对字符串的合法性进行检查。当然那可以在判断具有. . .这样的结构后进行判断每个参数是否超出255来判断是否合法。

int isipv4Str(char *buffer){
    char *p;
    int count = 0;
    p = strstr(buffer, ".");

    while(p != NULL){
        count++;
        p = strstr(p+1, ".");
    }
    if(count == 3){
        return 1;
    } else {
        return 0;
    }
}
原文地址:https://www.cnblogs.com/fogcell/p/6681855.html