Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ntohs() and ntohl() equivalent?

Tags:

c#

htonl

Are there net to host conversion functions in C#? Googling and not finding much. :P

like image 237
bobber205 Avatar asked Mar 10 '10 20:03

bobber205


People also ask

Are Htons and Ntohs the same?

htons() ntohs() When a host byte order is different from network (that means the host uses little-endian), htons() converts the data from little-endian to big-endian, and ntohs() converts from big-endian back to little-endian.

What are Htonl and Ntohl?

sys/types.h — typedef symbols and structures. htons() — Translate an unsigned short integer into network byte order. ntohl() — Translate a long integer into host byte order.

What are the purposes of the Ntohs () Htons () Nothl () and Htonl () functions in a socket program?

The htonl() and htons() functions shall return the argument value converted from host to network byte order. The ntohl() and ntohs() functions shall return the argument value converted from network to host byte order.

What is Ntohs in socket?

The ntohs() function translates a short integer from network byte order to host byte order. Parameter Description a. The unsigned short integer to be put into host byte order.


2 Answers

IPAddress.HostToNetworkOrder and IPAddress.NetworkToHostOrder?

Each method has overloads for 16, 32 and 64 bit integers.

like image 157
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet


The System.Memory nuget package includes the System.Buffers.Binary.BinaryPrimitives static class, which includes static methods for dealing with "endianness", including many overloads of ReverseEndianness. On dotnet core, HostToNetWorkOrder is implemented using these ReverseEndianness methods . On a little-endian architecture (which I think is all that support .NET) HostToNetworkOrder and ReverseEndianness methods have identical performance on dotnetcore.

On dotnet framework (net461) however, the performance of calling HostToNetworkOrder is slightly (not quite 2x) slower than calling ReverseEndianness.

I believe that the JIT compiler is actually special casing these methods to invoke the BSWAP x86 instruction. If you exactly duplicate the implementation of the ReverseEndianness(long) method in your own codebase, it will be nearly 4x slower than calling the System.Memory implementation; suggesting there is JIT magic happening.

like image 34
MarkPflug Avatar answered Sep 28 '22 05:09

MarkPflug