From the journey to tcp connection at sylhare/tcp. I thought it would ne nice to store it all here.
Introduction
TCP stands for Transfer Control Protocol.
TCP is connection-oriented, meaning an exclusive connection must first be established between client and server for communication to take place. The other one is UDP User Datagram Protocol, no connection for this one, it’s sending data and hoping for the best.
TCP’s job is to ensure that all data sent in a stream moves from Point A to Point B in correct order and intact.
Difference between TCP and HTTP
While TCP contains information about what data has or has not yet been received, HTTP contains specific instructions on how to read and process this data once it arrives.
HTTP is located at Layer 7 (data, application) of the OSI model (Open Systems Interconnection), TCP is at Layer 4 (segment, transport).
TCP and Sockets
Socket is an internal endpoint for sending or receiving data between two different processes on the same or different machines. It’s a way to talk to other computers using standard Unix file descriptors.
There are 4 types of sockets (stream, datagram, raw, sequenced packet).
Socket is layer 5 (data, Session), two computer should have a socket connection to exchange data. You can use TCP for the transport of that data.
Bytes and bits
So you send bytes with tcp, however depending on the protocol you are using, you need to specify certain bits, header and you might be confused when reading the rfc. So here is a bit of a refresher.
Representation
A bit is the most basic unit and can be either 1 or 0. A byte is a group of 8 bits (256 permutations 0000 0000 to 1111 1111)
Thus, one byte can represent a decimal number between 0 and 255. Usually computers handles bytes instead of bits.
Then there is hexadecimal of base 16, using both numbers: 0 to 9 and letters: A to F.
Usually you see hex values using 0x
in order not to confuse them with decimal values in certain cases.
hex byte dec
0x11 0001 0001 17
However I find it easier to use hex to represent bytes.
Signed bits
You can also handle negative number with bits using Two complements.
With 3 bits from 000
to 111
can give:
- from 0 to 7 (
000
is 0 and111
is seven) - from -4 to 3 using two’s complement (
100
is -4 and011
is 3)
The two’s complement of an N-bit number is defined as its complement with respect to 2N. For instance, for the three-bit number 010, the two’s complement is 110, because 1000 - 010 = 110 with 1000 a 4bits number and 010 is 0x2. The two’s complement is calculated by inverting the digits and adding one:
010
inverted gives101
plus001
gives110
.- So from 2 (
010
), you get -2 (110
).