Home > Software engineering >  Can you give some practical uses of socket.ntohl(x) ,.. in socket programming in python?
Can you give some practical uses of socket.ntohl(x) ,.. in socket programming in python?

Time:04-01

I was learing socket programming from python docks and i reach to these things :

socket.ntohl(x) Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

socket.ntohs(x) Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

Changed in version 3.10: Raises OverflowError if x does not fit in a 16-bit unsigned integer.

socket.htonl(x) Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

socket.htons(x) Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

So all i can do with these functions is just putting some integer inside parentheses and then i have the result :

import  socket

a=socket.ntohs(32) #example number

print(a)
 

result : 8192

Can you give some examples that makes sense with those functions?

CodePudding user response:

This is a question about which machines are using big endian vs little endian.

I'm not a user of IBM mainframes but it seems: https://www.ibm.com/docs/en/zos/2.4.0?topic=hosts-network-byte-order that they use big endian. IBM pcs however, use little endian.

The TCP/IP standard network byte order is big-endian so it depends on the machine where the application code will run and whether it is little or big endian. If there is a mismatch between your network and your hardware byte orders, you need to use a function like the one you indicated.

This is one example.

CodePudding user response:

Python's int has the same endianness as the processor it runs on.

In computer networks, while transmitting and receiving data packets, Big Endian Ordering is used.

Therefore, you have to convert before sending data to the network and after receiving data from the network depending on the architecture the python interpreter is running on.

See https://en.wikipedia.org/wiki/Endianness

  • Related