IPv6格式转换(全写转简写)
生活随笔
收集整理的這篇文章主要介紹了
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, 0for i in range(len(list_v)-1):if first == second and (list_v[i+1] != "0" or list_v[i] != "0"):continueelif first == second and list_v[i] == "0" and list_v[i+1] == "0":first, second = i, i+1elif list_v[i] == "0":second += 1else:breakif second == (len(list_v)-1) and list_v[-1] == "0":second += 1if 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 retdef 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格式转换(全写转简写)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 携程研发方向秋招专业笔试
- 下一篇: 用mount挂载远程服务器网络硬盘