NoFear

导航

数字IP-字符串IP-转换

Posted on 2012-04-17 11:29  Fear_Hao  阅读(1704)  评论(0编辑  收藏  举报
View Code
int DigitIpToStrIp(unsigned long ip, char *strip)
{
    unsigned long temp;

    temp = ip << 8 * 3; 
    unsigned int IP_first = temp >> 8 * 3;

    temp = ip << 8 * 2; 
    unsigned int IP_second= temp >> 8 * 3;

    temp = ip << 8 * 1; 
    unsigned int IP_thrid = temp >> 8 * 3;

    unsigned int IP_fourth=ip>> 8 * 3;

    sprintf(strip,"%d.%d.%d.%d",IP_first,IP_second,IP_thrid,IP_fourth );
    return yes;
}


unsigned long StrIpToDigitIp(const char* Ip , size_t IPlen)
{
    if (IPlen < 7)
        return -1;
    unsigned long ret;
    char copy_ip[15] = {0};
    memcpy(&copy_ip , Ip , IPlen);
    unsigned short int token[4], tokenindex = 0 , count = 0;
    for (unsigned short int index = 0;index < IPlen; index++)
    {
        if (copy_ip[index] == '.')
        {
            copy_ip[index] = '\0';
            token[3 - count] = atoi(&copy_ip[tokenindex]);
            tokenindex = index + 1;
            count ++;
        }
    }
    if (count != 3)
        return -1;
    token[0] = atoi(&copy_ip[tokenindex]);
    unsigned char temp[4];
    memcpy(&temp[0] , &token[3] , sizeof(unsigned char));
    memcpy(&temp[1] , &token[2] , sizeof(unsigned char));
    memcpy(&temp[2] , &token[1] , sizeof(unsigned char));
    memcpy(&temp[3] , &token[0] , sizeof(unsigned char));
    memcpy(&ret , &temp[0] , sizeof(unsigned long ));
    return ret;
}

unsigned long strip_digip(char *ip,int iplen)
{
    //192.168.52.11
    unsigned long ret = 0;

    char temp_ip[16] = {0};
    memcpy(temp_ip,ip,iplen);

    char *pos = temp_ip;
    int n = 0 , r = 0;

    char tmp_buf[8] = {0};
    unsigned char tmp_num;

    unsigned char num_buf[4] = {0};
    int num_idx = 0;
    
    while(1)
    {
        r = sscanf(pos,"%[^.].%n",tmp_buf,&n);
        if(r==1)
        {
            pos += n;
            tmp_num = atoi(tmp_buf);
            memcpy(&num_buf[num_idx],&tmp_num,1);
            num_idx++;
        }
        else
            break;
    }

    if(num_idx == 4)
        memcpy(&ret,num_buf,num_idx);

    return ret;