PageRenderTime 28ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/static/socket.html

https://github.com/manugarg/articles
HTML | 358 lines | 284 code | 72 blank | 2 comment | 0 complexity | 5a77dc0b78c5a6f8713dc2b9f2049362 MD5 | raw file
  1. <html>
  2. <head>
  3. <title>Mighty Sockets</title>
  4. <style type="text/css">
  5. body {
  6. font: 76% Verdana, sans-serif;
  7. color: #444;
  8. }
  9. .description {
  10. color: #444;
  11. background: #C7C7C7;
  12. padding: 3px 25px 2.2em 25px;
  13. margin: 0;
  14. line-height: 1;
  15. }
  16. p {
  17. margin: 1em 0;
  18. line-height: 1.5;
  19. }
  20. h1 {
  21. font-size: 2.0em;
  22. letter-spacing: 0.1em;
  23. }
  24. h2 {
  25. border-bottom-color: #eee;
  26. border-bottom-width: 3px;
  27. border-bottom-style: double;
  28. }
  29. pre {
  30. font-family: courier new;
  31. font-weight: bold;
  32. background-color: #FAFAFA;
  33. }
  34. blockquote {
  35. margin: 1em 2em;
  36. font-style: italic;
  37. font-size: 95%;
  38. }
  39. #author {
  40. font-size: 95%;
  41. float:left;
  42. padding: 2px 12px 2px 0px;
  43. }
  44. #container {
  45. width: 718px;
  46. text-align: left;
  47. margin: 0 auto;
  48. }
  49. #main-content {
  50. padding-top: 22px;
  51. }
  52. </style>
  53. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  54. </head>
  55. <body>
  56. <div id="container">
  57. <h1 id="page-title">Mighty Sockets</h1>
  58. <div id="header">
  59. <div id="author">By <a rel="author"
  60. href="https://plus.google.com/106265659371255351553?rel=author">Manu
  61. Garg</a> (<a href="http://www.manugarg.com">www.manugarg.com</a>) | </div>
  62. <div class="g-plusone" data-annotation="bubble" data-size="medium" data-width="300" data-href="http://articles.manugarg.com/socket.html"></div>
  63. </div>
  64. <h1>&nbsp;</h1>
  65. <pre>
  66. Sockets are indeed the window to networking and networking drives the
  67. whole world some way or other, that's why the name "Mighty Sockets".
  68. In simple terms, a socket is an endpoint of communication. And a
  69. connection is represented by a socket pair. Remember, not all
  70. communication is connection oriented. So, you can have a single socket
  71. also doing most of the job for you (e.g. UDP sockets). A process deals
  72. with the socket in the same way as it deals with files. We'll see more
  73. of this similarity in coming sections.
  74. 1. HOW DO WE CREATE THEM?
  75. ---------------------
  76. As always we have a system call to do the job for us :)
  77. int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  78. //socket(2) prototype: socket(int domain, int type, int protocol)
  79. What it says is - give me a socket of domain INET (AF_INET is for
  80. Address Famiy - INET) and of type SOCK_STREAM (stream socket) and
  81. default protocol that goes with streaming sockets (it's TCP).
  82. Socket system call does a lot of things behind the scene. It creates
  83. socket structure in kernel memory. This structure is then filled by
  84. various protocol independent data and other data depending upon the
  85. address family, type and protocol.
  86. 2. NAMING THE SOCKET:
  87. -----------------
  88. Naming or addressing of a socket is very important. This is how data is
  89. supposed to reach right process.
  90. How sockets are addressed depends upon the domain of the socket. For
  91. example, an INET domain socket is identified by ip address and port
  92. combined. Of course, IP address is required if you want to reach a
  93. machine. IP address is used by inernet protocol to route the data from
  94. one machine to other machine. Port is required by kernel to route the
  95. packet to the right process.
  96. So as you see naming of a socket is important. But, you don't have to do
  97. this yourself always. If a specific port number is not required by an
  98. application process (as is the case for most of the client), kernel may
  99. assign a port to the socket internally. However, if you are looking for
  100. a specific port as in case of a server, you need to do get it through
  101. 'bind(2)' system call:
  102. int bind(int sockfd, struct sockaddr *my_addr, socklen_t
  103. addrlen);
  104. "sockaddr" structure has fields like socket family (AF_INET), IP address
  105. (for IP) and Port. struct sockaddr is a generic structure. Generally we
  106. fill information in a more specific structure like sockaddr_in for
  107. domain INET.
  108. This way we bind the socket to specific address, or in other way we give
  109. our socket a name. As mentioned earlier, this is required generally only in
  110. case of server, when we want a specific port for ourselves.
  111. 3. CONNECTION ESTABLISHMENT:
  112. ------------------------
  113. Connection establishment is required for all connection oriented
  114. protocols (like TCP). In TCP terminology, a connection is established
  115. using three-way handshake. A SYN packet is sent from one side
  116. (generally client) and when that packet arrives, receiving end
  117. (generally server) sends a [SYN,ACK] and connection is complete, when
  118. server receives ACK from client.
  119. active passive
  120. | SYN |
  121. |-------------->|
  122. | [SYN, ACK] |
  123. |&lt;------------- |
  124. | ACK |
  125. |-------------->|
  126. | |
  127. There are 2 possible ways to establish a connection: Whether you want to
  128. initiate the connection or wait for the connection. If you choose to
  129. wait for a connection (e.g. you are a server), you do a 'passive open'
  130. and if you want initiate the connection (e.g. you are client and want
  131. something done from server), you do an 'active open'.
  132. 3.1 PASSIVE OPEN:
  133. ------------
  134. If you are doing passive open, you are waiting for the connection.
  135. Waiting for a connection is also called 'listening'. Your server starts
  136. listening when it executes:
  137. listen(backlog);
  138. "The 'listen' function converts an unconnected socket into a passive
  139. socket, indicating that the kernel should accept incoming connection
  140. requests directed to this socket."
  141. For a given listening socket kernel maintains 2 queues:
  142. i) An 'incomplete conneciton queue', which contains an entry for all
  143. unacknowledged connections. Basically, I have received the SYN from the
  144. other machine, sent the [SYN, ACK] and waiting for ACK from other side.
  145. These sockets are in SYN_RCVD state.
  146. ii) A 'completed connection queue', which contains an entry for each
  147. machine with whom the TCP three-way handshake is completed. These
  148. sockets are in ESTABLISHED state.
  149. Sum of the both queues cannot exceed backlog.
  150. _______________________
  151. | _______ |
  152. | |Server | |
  153. | |_______| |
  154. listening &lt;-----|------ (*.1200,*.*) |
  155. socket |_______________________|
  156. fig. 1
  157. Above figure, represents a server listening at port 1200. No connection
  158. has been established yet.
  159. Fetching Connections:
  160. --------------------
  161. Connections, if any, are still with the TCP. To return a connection to
  162. the application
  163. int new_sock = accept(int orig_sock, struct sockaddr* addr,
  164. socklen_t *addrlen);
  165. 'accept' is called by an application to return the next completed
  166. connection from the front of the completed connection queue. If the
  167. completed connection queue is empty the process is put to sleep
  168. (assuming the default of a blocking socket).
  169. If 'accept' is successful, its return value is a brand new descriptor
  170. that was automatically created by kernel. This new descriptor refers to
  171. the TCP connection with the client. Listening socket remains untouched.
  172. Client socket address and length information is filled by accept. Server
  173. may or may not use them.
  174. So you have 2 sockets now, one listening and other already connected.
  175. You may close orig_sock, if you have no use for it now (eg. don't want
  176. to continue listening).
  177. _______________________ _______________________
  178. | _______ | | _______ |
  179. | |Server | | |-----> |Client | |
  180. | |_______| | /| |_______| |
  181. listening----->(*.1200,*.*) | / |(3.209.127.100:1500, |
  182. socket | _______ | / | 3.209.129.47:1200) |
  183. | |Server | | / |_______________________|
  184. | |_______| | / 3.209.127.100
  185. | (3.209.129.47:1200,&lt;--|-/
  186. | 3.209.127.100:1500) |
  187. |_______________________|
  188. 3.209.129.47
  189. Figure 2
  190. 3.2 ACTIVE OPEN:
  191. -----------
  192. When you initiate a connection, you are doing an 'active open'. You just
  193. need to call 'connect(2)' to initiate a connection.
  194. int connect(int sockfd, const struct sockaddr *serv_addr,
  195. socklen_t addrlen);
  196. This initiates the process of connection (3-way handshake in TCP
  197. teminology) and returns only when connection is complete (or something
  198. goes wrong with your luck like signals and all). If not able to
  199. establish connection, it returns -1 and sets errno.
  200. When you call connect, kernel implicitly allocates a port to the socket
  201. (naming of socket). Fig. 2 has a client connected to the server. Port
  202. 1500 is allocated to the client implicitly by kernel.
  203. 4. DATA TRANSFER:
  204. -------------
  205. Now next obvious step will be to get some work done with this socket.
  206. Mechanism for sending and receiving data is actually very simple. You
  207. have to just read, write the socket descriptor like file descriptor.
  208. But, what happens behind the scenes is more important (like always ;)).
  209. A lot can be said by sockets. But, I'll just talk about packets
  210. demultiplexing, which is handled by TCP-IP.
  211. 5. DEMULTIPLEXING:
  212. --------------
  213. Ok, so now you have a connection. Now client sends some data to server,
  214. say a request for a web page in case of web client. How does it reach
  215. the server? Packet carries the information like source address (ip and
  216. port) and destination address. IP does all the work to make the packet
  217. reach destination machine using dst IP address.
  218. But now what, we have 2 sockets on the server with the same name ie.
  219. with same ports (remember one socket listening and other connected to
  220. the client). And there can be many more sockets with the same name
  221. depending upon the number of clients connected at a time. Here comes TCP
  222. to rescue. TCP demultiplexes incoming segments for us.
  223. TCP cannot demulitplex incoming segments by looking at just the
  224. destination port number. TCP must look at all 4 elements in the socket
  225. pair to determine which endpoint receives the arriving segment.
  226. _______________________ _______________________
  227. | _______ | | _______ |
  228. | |Server | | --|-----> |Client | |
  229. | |_______| | / | |_______| |
  230. | (*.1200,*.*) | / |(3.209.127.100:1500, |
  231. | _______ | / | 3.209.129.47:1200) |
  232. | |Server | &lt;----|-/ | _______ |
  233. | |__c_1__| | --|-----> |Client | |
  234. | (3.209.129.47:1200, | / | |_______| |
  235. | 3.209.127.100:1500) | / |(3.209.127.100:1501, |
  236. | _______ | / | 3.209.129.47:1200) |
  237. | |Server | &lt;----|-/ |_______________________|
  238. | |__c_2__| | 3.209.127.100
  239. | (3.209.129.47:1200, |
  240. | 3.209.127.100:1501) |
  241. | |
  242. |_______________________|
  243. 3.209.129.47
  244. Figure 3
  245. In figure 3, we have 2 connections open between server machine and client
  246. machine. It's a case of concurrent servers (most typical way to handle
  247. clients). In this case, when a new connection arrives, server forks out
  248. and lets his child handle the connection and himself keeps listening for
  249. new connections.
  250. Here we have 3 sockets with the same local port (1200). If a segment
  251. arrives from 3.209.127.100 port 1500 destined for port 1200, it is
  252. delivered to first child. If a segment arrives from 3.209.127.100 port
  253. 1501 destined for 3.209.129.47 port 1200, it is delivered to the second
  254. child. All other segments destined for port 1200 are delivered to the
  255. original server with the listening socket.
  256. There is a lot more to talk about sockets. But, there is a lot more
  257. documentation too. This is just an attempt to explain what most other
  258. documents miss to explain.
  259. </pre>
  260. <hr>
  261. <div id="g_footer">Copyright 2006 <a rel="author"
  262. href="https://plus.google.com/106265659371255351553?rel=author">Manu Garg+</a>.</div>
  263. <script type="text/javascript">
  264. var sc_project=825718;
  265. var sc_invisible=0;
  266. var sc_partition=6;
  267. var sc_security="ec98e57b";
  268. </script>
  269. <script type="text/javascript"
  270. src="http://www.statcounter.com/counter/counter_xhtml.js"></script><noscript><div
  271. class="statcounter"><a class="statcounter"
  272. href="http://www.statcounter.com/"><img class="statcounter"
  273. src="http://c7.statcounter.com/counter.php?sc_project=825718&java=0&security=ec98e57b&invisible=0"
  274. alt="blog stats" /></a></div></noscript>
  275. <!-- End of StatCounter Code -->
  276. </div>
  277. <!-- Google Plus One Button. -->
  278. <script type="text/javascript">
  279. (function() {
  280. var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
  281. po.src = 'https://apis.google.com/js/plusone.js';
  282. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  283. })();
  284. </script>
  285. </body
  286. </html>