PageRenderTime 35ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/static/socket.txt

https://github.com/manugarg/articles
Plain Text | 258 lines | 199 code | 59 blank | 0 comment | 0 complexity | 02736583872b359969a2c0546de5e149 MD5 | raw file
  1. MIGHTY SOCKETS
  2. ==============
  3. Sockets are indeed the window to networking and networking drives the
  4. whole world some way or other, that's why the name "Mighty Sockets".
  5. In simple terms, a socket is an endpoint of communication. And a
  6. connection is represented by a socket pair. Remember, not all
  7. communication is connection oriented. So, you can have a single socket
  8. also doing most of the job for you (e.g. UDP sockets). A process deals
  9. with the socket in the same way as it deals with files. We'll see more
  10. of this similarity in coming sections.
  11. 1. HOW DO WE CREATE THEM?
  12. ---------------------
  13. As always we have a system call to do the job for us :)
  14. int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  15. //socket(2) prototype: socket(int domain, int type, int protocol)
  16. What it says is - give me a socket of domain INET (AF_INET is for
  17. Address Famiy - INET) and of type SOCK_STREAM (stream socket) and
  18. default protocol that goes with streaming sockets (it's TCP).
  19. Socket system call does a lot of things behind the scene. It creates
  20. socket structure in kernel memory. This structure is then filled by
  21. various protocol independent data and other data depending upon the
  22. address family, type and protocol.
  23. 2. NAMING THE SOCKET:
  24. -----------------
  25. Naming or addressing of a socket is very important. This is how data is
  26. supposed to reach right process.
  27. How sockets are addressed depends upon the domain of the socket. For
  28. example, an INET domain socket is identified by ip address and port
  29. combined. Of course, IP address is required if you want to reach a
  30. machine. IP address is used by inernet protocol to route the data from
  31. one machine to other machine. Port is required by kernel to route the
  32. packet to the right process.
  33. So as you see naming of a socket is important. But, you don't have to do
  34. this yourself always. If a specific port number is not required by an
  35. application process (as is the case for most of the client), kernel may
  36. assign a port to the socket internally. However, if you are looking for
  37. a specific port as in case of a server, you need to do get it through
  38. 'bind(2)' system call:
  39. int bind(int sockfd, struct sockaddr *my_addr, socklen_t
  40. addrlen);
  41. "sockaddr" structure has fields like socket family (AF_INET), IP address
  42. (for IP) and Port. struct sockaddr is a generic structure. Generally we
  43. fill information in a more specific structure like sockaddr_in for
  44. domain INET.
  45. This way we bind the socket to specific address, or in other way we give
  46. our socket a name. As mentioned earlier, this is required generally only in
  47. case of server, when we want a specific port for ourselves.
  48. 3. CONNECTION ESTABLISHMENT:
  49. ------------------------
  50. Connection establishment is required for all connection oriented
  51. protocols (like TCP). In TCP terminology, a connection is established
  52. using three-way handshake. A SYN packet is sent from one side
  53. (generally client) and when that packet arrives, receiving end
  54. (generally server) sends a [SYN,ACK] and connection is complete, when
  55. server receives ACK from client.
  56. active passive
  57. | SYN |
  58. |-------------->|
  59. | [SYN, ACK] |
  60. |<------------- |
  61. | ACK |
  62. |-------------->|
  63. | |
  64. There are 2 possible ways to establish a connection: Whether you want to
  65. initiate the connection or wait for the connection. If you choose to
  66. wait for a connection (e.g. you are a server), you do a 'passive open'
  67. and if you want initiate the connection (e.g. you are client and want
  68. something done from server), you do an 'active open'.
  69. 3.1 PASSIVE OPEN:
  70. ------------
  71. If you are doing passive open, you are waiting for the connection.
  72. Waiting for a connection is also called 'listening'. Your server starts
  73. listening when it executes:
  74. listen(backlog);
  75. "The 'listen' function converts an unconnected socket into a passive
  76. socket, indicating that the kernel should accept incoming connection
  77. requests directed to this socket."
  78. For a given listening socket kernel maintains 2 queues:
  79. i) An 'incomplete conneciton queue', which contains an entry for all
  80. unacknowledged connections. Basically, I have received the SYN from the
  81. other machine, sent the [SYN, ACK] and waiting for ACK from other side.
  82. These sockets are in SYN_RCVD state.
  83. ii) A 'completed connection queue', which contains an entry for each
  84. machine with whom the TCP three-way handshake is completed. These
  85. sockets are in ESTABLISHED state.
  86. Sum of the both queues cannot exceed backlog.
  87. _______________________
  88. | _______ |
  89. | |Server | |
  90. | |_______| |
  91. listening <-----|------ (*.1200,*.*) |
  92. socket |_______________________|
  93. fig. 1
  94. Above figure, represents a server listening at port 1200. No connection
  95. has been established yet.
  96. Fetching Connections:
  97. --------------------
  98. Connections, if any, are still with the TCP. To return a connection to
  99. the application
  100. int new_sock = accept(int orig_sock, struct sockaddr* addr,
  101. socklen_t *addrlen);
  102. 'accept' is called by an application to return the next completed
  103. connection from the front of the completed connection queue. If the
  104. completed connection queue is empty the process is put to sleep
  105. (assuming the default of a blocking socket).
  106. If 'accept' is successful, its return value is a brand new descriptor
  107. that was automatically created by kernel. This new descriptor refers to
  108. the TCP connection with the client. Listening socket remains untouched.
  109. Client socket address and length information is filled by accept. Server
  110. may or may not use them.
  111. So you have 2 sockets now, one listening and other already connected.
  112. You may close orig_sock, if you have no use for it now (eg. don't want
  113. to continue listening).
  114. _______________________ _______________________
  115. | _______ | | _______ |
  116. | |Server | | |-----> |Client | |
  117. | |_______| | /| |_______| |
  118. listening----->(*.1200,*.*) | / |(3.209.127.100:1500, |
  119. socket | _______ | / | 3.209.129.47:1200) |
  120. | |Server | | / |_______________________|
  121. | |_______| | / 3.209.127.100
  122. | (3.209.129.47:1200,<--|-/
  123. | 3.209.127.100:1500) |
  124. |_______________________|
  125. 3.209.129.47
  126. Figure 2
  127. 3.2 ACTIVE OPEN:
  128. -----------
  129. When you initiate a connection, you are doing an 'active open'. You just
  130. need to call 'connect(2)' to initiate a connection.
  131. int connect(int sockfd, const struct sockaddr *serv_addr,
  132. socklen_t addrlen);
  133. This initiates the process of connection (3-way handshake in TCP
  134. teminology) and returns only when connection is complete (or something
  135. goes wrong with your luck like signals and all). If not able to
  136. establish connection, it returns -1 and sets errno.
  137. When you call connect, kernel implicitly allocates a port to the socket
  138. (naming of socket). Fig. 2 has a client connected to the server. Port
  139. 1500 is allocated to the client implicitly by kernel.
  140. 4. DATA TRANSFER:
  141. -------------
  142. Now next obvious step will be to get some work done with this socket.
  143. Mechanism for sending and receiving data is actually very simple. You
  144. have to just read, write the socket descriptor like file descriptor.
  145. But, what happens behind the scenes is more important (like always ;)).
  146. A lot can be said by sockets. But, I'll just talk about packets
  147. demultiplexing, which is handled by TCP-IP.
  148. 5. DEMULTIPLEXING:
  149. --------------
  150. Ok, so now you have a connection. Now client sends some data to server,
  151. say a request for a web page in case of web client. How does it reach
  152. the server? Packet carries the information like source address (ip and
  153. port) and destination address. IP does all the work to make the packet
  154. reach destination machine using dst IP address.
  155. But now what, we have 2 sockets on the server with the same name ie.
  156. with same ports (remember one socket listening and other connected to
  157. the client). And there can be many more sockets with the same name
  158. depending upon the number of clients connected at a time. Here comes TCP
  159. to rescue. TCP demultiplexes incoming segments for us.
  160. TCP cannot demulitplex incoming segments by looking at just the
  161. destination port number. TCP must look at all 4 elements in the socket
  162. pair to determine which endpoint receives the arriving segment.
  163. _______________________ _______________________
  164. | _______ | | _______ |
  165. | |Server | | --|-----> |Client | |
  166. | |_______| | / | |_______| |
  167. | (*.1200,*.*) | / |(3.209.127.100:1500, |
  168. | _______ | / | 3.209.129.47:1200) |
  169. | |Server | <----|-/ | _______ |
  170. | |__c_1__| | --|-----> |Client | |
  171. | (3.209.129.47:1200, | / | |_______| |
  172. | 3.209.127.100:1500) | / |(3.209.127.100:1501, |
  173. | _______ | / | 3.209.129.47:1200) |
  174. | |Server | <----|-/ |_______________________|
  175. | |__c_2__| | 3.209.127.100
  176. | (3.209.129.47:1200, |
  177. | 3.209.127.100:1501) |
  178. | |
  179. |_______________________|
  180. 3.209.129.47
  181. Figure 3
  182. In figure 3, we have 2 connections open between server machine and client
  183. machine. It's a case of concurrent servers (most typical way to handle
  184. clients). In this case, when a new connection arrives, server forks out
  185. and lets his child handle the connection and himself keeps listening for
  186. new connections.
  187. Here we have 3 sockets with the same local port (1200). If a segment
  188. arrives from 3.209.127.100 port 1500 destined for port 1200, it is
  189. delivered to first child. If a segment arrives from 3.209.127.100 port
  190. 1501 destined for 3.209.129.47 port 1200, it is delivered to the second
  191. child. All other segments destined for port 1200 are delivered to the
  192. original server with the listening socket.
  193. There is a lot more to talk about sockets. But, there is a lot more
  194. documentation too. This is just an attempt to explain what most other
  195. documents miss to explain.
  196. -----------------------------------------------------------------------
  197. Author: Manu Garg
  198. http://www.manugarg.com
  199. manugarg at gmail.com