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.

Tagged #c, #networking.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2016. Content is not associated with my employer. Found an error? Edit this page.