我是靠谱客的博主 单薄板凳,最近开发中收集的这篇文章主要介绍IPv6格式转换(全写转简写),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

有些需要支持ipv6的功能,在展示ip时当然是展示简写ip,但是在收包的时候都是全写ip,需要将其转换:

# -*- coding=UTF-8 -*-
def ipv6_trans(addr_v6):
    list_v = []
    for x in addr_v6.split(":"):
        if x == "0000" or x == "0":
            list_v.append("0")
        else:
            list_v.append(x.lstrip("0"))

    first, second = 0, 0
    for i in range(len(list_v)-1):
        if first == second and (list_v[i+1] != "0" or list_v[i] != "0"):
            continue
        elif first == second and list_v[i] == "0" and list_v[i+1] == "0":
            first, second = i, i+1
        elif list_v[i] == "0":
            second += 1
        else:
            break

    if second == (len(list_v)-1) and list_v[-1] == "0":
        second += 1

    if first != second:
        a, b, c = list_v[0: first], list_v[first: second], list_v[second:]
        ret = ":".join(a) + "::" + ":".join(c)
    else:
        ret = ":".join(list_v)

    return ret

def main():
    # ipv6 = "ff06:0:0:0:0:0:0:c3"
    ipv6_1 = "0000:ff06:0000:0000:0000:0000:0000:0000"
    ipv6_2 = "0000:0000:0000:0000:0000:0000:0000:0000"
    ipv6_3 = "ff02:0000:0000:0000:0000:0001:ff00:0001"
    ipv6_4 = "fd82:139b:8752:0000:246e:0031:888c:36db"
    ipv6_5 = "fd82:0000:8752:0000:0000:0031:888c:36db"
    ipv6_6 = "fd82:0000:0000:8752:0000:0031:888c:36db"
    ipv6_list = [ipv6_1, ipv6_2, ipv6_3, ipv6_4, ipv6_5, ipv6_6]
    for element in ipv6_list:
        print(ipv6_trans(element))

if __name__ == '__main__':
    main()

输出结果:

0:ff06::
::
ff02::1:ff00:1
fd82:139b:8752:0:246e:31:888c:36db
fd82:0:8752::31:888c:36db
fd82::8752:0:31:888c:36db

最后

以上就是单薄板凳为你收集整理的IPv6格式转换(全写转简写)的全部内容,希望文章能够帮你解决IPv6格式转换(全写转简写)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部