Learn more about Russian war crimes in Ukraine.

What is htons in C?

When we do socket programming, we have to convert integer values using functions called htons and htonl, like this:

#include <arpa/inet.h>
int main() {
  int server_fd = socket(AF_INET, SOCK_STREAM, 0);
  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons(8080);
  server.sin_addr.s_addr = htonl(INADDR_ANY);
  // ...
  return 0;

What are these htons and htonl functions?

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);   // "Host TO Network Long"
uint16_t htons(uint16_t hostshort);  // "Host TO Network Short"

These functions “convert values between host and network byte order”, where “Network byte order is big endian, or most significant byte first.” There are equivalent inverse functions ntohl and ntohs.

What is meant by “network byte order”? I don’t think it’s very well defined. I think it refers to the fact that a variety of network things use MSB order, including Ethernet frames and IPv4 packets. Presumably, we have to convert our numbers to MSB order because the kernel wants to copy them byte-for-byte into the IP packet.

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.