Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3235312
  • 博文数量: 346
  • 博客积分: 10189
  • 博客等级: 上将
  • 技术积分: 3125
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-05 19:46
文章分类

全部博文(346)

文章存档

2013年(35)

2011年(35)

2010年(76)

2009年(48)

2008年(152)

分类: C/C++

2011-05-30 10:13:04

IPV6省略地址的变换函数,如
输入1080:0000:0000:0000:0008:0800:200C:417A,输出结果为:1080::0:8:800:200C:417A
输入0000:0000:0000:0000:0000:0000:0A00:0001,输出结果为:::A00:1
 
   
/************************************************************************/
/* Define     : IPv6地址省略形式作成           
/* InParam    : ipv6 为IPV6的地址                    
/* OutParam   : dst 位输出的字符串形式               
/* Return     : OK 正常終了                                     
/*                   NG 错误                                          
/* Created    : 2006/02/16                                             
/* LastUpdated: 2006/03/30                                            
/************************************************************************/
ERRCLI    GetPv6Addr( char ipv6[ 16 ], char *dst )
{
    int     i;
    int     start = -1;
    int     count = 0;
    int     ls_start = -1;
    int     ls_count = 0;
    char    wk[ 16 ];

    /* 求省略位置(start)和个数(count) */
    for( i=0; i<15; i+=2 )
    {
        if( 0 == ipv6[ i ] && 0 == ipv6[ i+1 ] )
        {
            /* 0开始位置保存 */
            if( -1 == ls_start )
            {
                ls_start = i;
            }
            ls_count++;
        }
        else
        {
            if( -1 != ls_start )
            {
                /* 如果位连续的0,则更新 */
                if( ls_count > count )
                {
                    start = ls_start;
                    count = ls_count;
                }

                ls_start = -1;
                ls_count = 0;
            }
        }
    }

    if( -1 != ls_start )
    {
        if( ls_count > count )
        {
            start = ls_start;
            count = ls_count;
        }
    }

    /* IPv6文字作成 */
    memset( dst, 0, sizeof(dst) );

    for( i=0; i<15; i+=2 )
    {
        if( i == start )
        {
            strcat(dst,":");

            i = i+( 2 * (count-1) );

            /* 如果是最后加':' */
            if( i == 14 )
            {
                strcat(dst,":");
            }
        }
        else
        {
            sprintf( wk, "%s%x", ((i==0)?(""):(":")), ntohs(*(uint16*)&ipv6[ i]) );

            strcat(dst, wk);
        }
    }
    return OK;
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zzh_haiz/archive/2007/07/24/1705288.aspx

阅读(2721) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~