Initializing a socket object

Viewed 88

When setting up a socket objects, I use:

socket.socket()

Which, written more verbosely (also what it defaults to) is:

socket.socket(socket.AF_INET, socket.SOCK_STREAM)

A few questions on this:

socket.AF_INET allows me to pass to pass a host/port, that is, an ipv4 address. Why is the convention to call it AF_INET (and not, for example, socket.IPV4. What does that stand for?

What is SOCK_STREAM? Does this just mean it's going to accept an HTTP request, or something else? Also, what would be the difference between using SOCK_STREAM and SOCK_RAW ?

2 Answers

The name AF_INET was copied from Unix, it's short for "InterNET". The abbreviation was created many years before IPv6 was designed, there was just one Internet protocol, so the idea of calling it IPV4 didn't come into the designer's minds.

AF stands for "Address Family", meaning that the protocol uses Internet addresses. There's also PF, which stands for "Protocol Family". At the time this was designed, there was the idea that there might be multiple protocols that use the same form of addressing, so they separated these concepts, but in practice they turned out to be one-to-one, so the distinction faded away (all the AF_xxx constants have the same values as the corresponding PF_xxx constants).

SOCK_STREAM means that the socket transfers a stream of bytes. The alternative is SOCK_DGRAM, which transfers messages as distinct units called "datagrams".

All names are "borrowed" from [man7]: SOCKET(2) (man socket).

What do different abbreviations stand for:

  • AF_ - Address Family
  • _INET - Internet (IPv4 - existing at that time). Full spec: [IETF.Tools]: INTERNET PROTOCOL
  • SOCK_ - Socket
  • _DGRAM - Connectionless datagram (usually UDP protocol)
  • _STREAM - Connection byte stream (usually TCP protocol)
  • _RAW - Raw ("unprocessed") network protocol (or raw sockets: [man7]: RAW(7))
Related