python通過ntohl和htonl等函數實現主機位元組序和網路位元組序相互轉換

來源:互聯網
上載者:User

標籤:python通過ntohl和htonl等函數實現主機位元組序和網路位元組序之間相互轉換

    Python的socket庫提供了將資料在網路位元組序和主機位元組序之間相互轉換的函數。有什麼作用呢?

在編寫低層網路應用時,或許需要處理通過電纜在兩台裝置之間傳送的低層資料。在這種操作中,需要把主機作業系統發出的資料轉換成網路格式,或者做逆向轉換,因為這兩種資料的表示方式不一樣。


技術點解析:

1、定義convert_integer()函數,注意函數格式(以後都會提醒這個,要養成習慣)

2、socket庫中的類函數 

ntohl() 把網路位元組序轉換成了長整形主機位元組序

htonl() 把長整形主機位元組序轉換成了網路位元組序

函數名中的n表示網路; h表示主機; l表示長整形即32位; s表示短整形即16位。

3、測試為整數型轉換函式

4、print列印輸入類型對應多列,是一一相互對應的


代碼如下:

import  socketdef convert_integer():    data=1234567890    # 16-bit    print("Original: %s => Short host byte order: %s, Network byte order: %s" %(data,socket.ntohs(data),socket.htons(data)))    # 32-bit    print("Original: %s => Long host byte order: %s, Network byte order: %s" %(data,socket.ntohl(data),socket.htonl(data)))

運行結果:

650) this.width=650;" src="https://s4.51cto.com/wyfs02/M02/9E/90/wKioL1mTrC3w7HPrAAA_Ac4lZto815.jpg" title="QQ20170816101951.jpg" width="720" height="91" border="0" hspace="0" vspace="0" style="width:720px;height:91px;" alt="wKioL1mTrC3w7HPrAAA_Ac4lZto815.jpg" />


本文出自 “老白的部落格” 部落格,請務必保留此出處http://laobaiv1.blog.51cto.com/2893832/1956663

python通過ntohl和htonl等函數實現主機位元組序和網路位元組序相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.