Python Network Programming(4)---主机字节序与网络字节序之间的相互转换

本文介绍在低层网络应用开发过程中,如何使用Python的socket库进行网络字节序与主机字节序之间的转换。这些转换对于确保跨平台数据一致性至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写低层网络应用时,或许需要处理通过电缆在两台设备之间传送的低层数据,这种操作中,需要把主机操作系统发出的数据转换成网络格式,或者做逆向转换,因为这两种数据的表示方式不一样。

字节序相关见unp。

Python的socket提供数据在网络字节序与主机字节序之间相互转换的函数:htonl,ntohl;htons,ntohs。

__author__ = 'liyuan35023'

#!/home/mimiasd/PycharmProjects/workspace python27

import socket

def convert_integer():
    data = 1234
    # 32bits
    print "original: %s => Long host: %s, Long network: %s"\
        % (data, socket.ntohl(data), socket.htonl(data))
    # 16bits
    print "original: %s => Short host: %s, Short network: %s"\
        % (data, socket.ntohs(data), socket.htons(data))

if __name__ == "__main__":
    convert_integer()
Utilize Python 3 to get network applications up and running quickly and easily About This Book Leverage your Python programming skills to build powerful network applications Explore steps to interact with a wide range of network services Design multithreaded and event-driven architectures for echo and chat servers Who This Book Is For If you're a Python developer or a system administrator with Python experience and you're looking to take your first steps in network programming, then this book is for you. Basic knowledge of Python is assumed. In Detail Network programming has always been a demanding task. With full-featured and well documented libraries all the way up the stack, Python makes network programming the enjoyable experience it should be. Starting with a walkthrough of today's major networking protocols, with this book you'll learn how to employ Python for network programming, how to request and retrieve web resources, and how to extract data in major formats over the Web. You'll utilize Python for e-mailing using different protocols and you'll interact with remote systems and IP and DNS networking. As the book progresses, socket programming will be covered, followed by how to design servers and the pros and cons of multithreaded and event-driven architectures. You'll develop practical client-side applications, including web API clients, e-mail clients, SSH, and FTP. These applications will also be implemented through existing web application frameworks. Table of Contents Chapter 1. Network Programming and Python Chapter 2. HTTP and Working with the Web Chapter 3. APIs in Action Chapter 4. Engaging with E-mails Chapter 5. Interacting with Remote Systems Chapter 6. IP and DNS Chapter 7. Programming with Sockets Chapter 8. Client and Server Applications Chapter 9. Applications for the Web
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值