├── LICENSE ├── README ├── basic ├── Makefile ├── README ├── client.c └── server.c ├── bittorent └── README ├── chat ├── Makefile ├── README ├── chatclient.c └── chatserver.c └── p2p └── README /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | socketfun 2 | --------- 3 | 4 | socketfun is a collection of well commented socket programming code. 5 | Error checking is not performed for purpose of brevity and readability. 6 | 7 | check README files in each directory for more details. 8 | 9 | status 10 | ------ 11 | work in progress 12 | 13 | appreciate 14 | ---------- 15 | I really appreciate opening issues, if you see any. 16 | -------------------------------------------------------------------------------- /basic/Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | 3 | CFLAGS = -std=c90 -Wall -Wwrite-strings 4 | 5 | SERVER_TARGET = server 6 | CLIENT_TARGET = client 7 | 8 | all: $(SERVER_TARGET) $(CLIENT_TARGET) 9 | 10 | $(SERVER_TARGET): $(SERVER_TARGET).c 11 | $(CC) $(CFLAGS) -o $(SERVER_TARGET) $(SERVER_TARGET).c 12 | 13 | $(CLIENT_TARGET): $(CLIENT_TARGET).c 14 | $(CC) $(CFLAGS) -o $(CLIENT_TARGET) $(CLIENT_TARGET).c 15 | 16 | clean: 17 | rm $(SERVER_TARGET) $(CLIENT_TARGET) 18 | -------------------------------------------------------------------------------- /basic/README: -------------------------------------------------------------------------------- 1 | socketfun - basic 2 | ----------------- 3 | 4 | This accomplishes a rudimentary server and clients that can communicate with the server. 5 | The client is prompted to enter a username. 6 | If "arjun024" is entered as username the server replies "Authentication successful", 7 | else it replies "Authentication failed". 8 | Error checking is not performed for purpose of brevity and readability. 9 | 10 | build instructions 11 | -------------------------- 12 | $ gcc -o server -std=c90 -Wall -Wwrite-strings server.c 13 | $ gcc -o client -std=c90 -Wall -Wwrite-strings client.c 14 | 15 | or do 16 | 17 | $ make 18 | 19 | running 20 | ------- 21 | $ ./server 22 | 23 | On a different teminal 24 | 25 | $ ./client 26 | 27 | clean up 28 | -------- 29 | $ make clean 30 | -------------------------------------------------------------------------------- /basic/client.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Arjun Sreedharan 3 | * License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define BUFF_SIZE 256 14 | 15 | static unsigned short port = 55555; 16 | 17 | void interact_with_server(int sfd) 18 | { 19 | char buffer[BUFF_SIZE] = {0}; 20 | /* Wait til receiving "You are now connected.\nEnter username:" */ 21 | read(sfd, buffer, sizeof buffer); 22 | /* clear buffer */ 23 | memset(buffer, 0, sizeof buffer); 24 | 25 | printf("%s\n", "Enter your username:"); 26 | /* read username */ 27 | fgets(buffer, sizeof buffer, stdin); 28 | buffer[strlen(buffer) - 1] = '\0'; 29 | 30 | /* send username to server*/ 31 | write(sfd, buffer, strlen(buffer)); 32 | 33 | /* clear buffer */ 34 | memset(buffer, 0, sizeof buffer); 35 | /* Wait til receiving server's response to username */ 36 | read(sfd, buffer, sizeof buffer); 37 | printf("%s\n", buffer); 38 | return; 39 | } 40 | 41 | int main(void) 42 | { 43 | int sockfd; 44 | 45 | /* 46 | * struct sockaddr defines a socket address. 47 | * A socket address is a combination of address family, 48 | * ip address and port. 49 | * For IP sockets, we may use struct sockaddr_in which is 50 | * just a wrapper around struct sockaddr. 51 | * Funtions like bind() etc are only aware of struct sockaddr. 52 | */ 53 | struct sockaddr_in serv_addr; 54 | 55 | /* 56 | * creates a socket of family Internet sockets (AF_INET) and 57 | * of type stream. 0 indicates to system to choose appropriate 58 | * protocol (eg: TCP) 59 | */ 60 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 61 | 62 | /* 63 | * Socket adddress represented by struct sockaddr: 64 | * first 2 bytes: Address Family, 65 | * next 2 bytes: port, 66 | * next 4 bytes: ipaddr, 67 | * next 8 bytes: zeroes 68 | */ 69 | /* 70 | * htons() and htonl() change endianness to 71 | * network order which is the standard for network 72 | * communication. 73 | */ 74 | 75 | serv_addr.sin_family = AF_INET; 76 | serv_addr.sin_port = htons(port); 77 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 78 | 79 | /* 80 | * The above achieves what could be done using the following 81 | * on a little endian machine. 82 | * This breaks if the structure has padding 83 | char filler[16] = {0}; 84 | filler[0] = AF_INET & 0xFF; 85 | filler[1] = AF_INET >> 8 & 0xFF; 86 | filler[2] = htons(port) & 0xFF; 87 | filler[3] = htons(port) >> 8 & 0xFF; 88 | filler[4] = htonl(INADDR_ANY) & 0xFF; 89 | filler[5] = htonl(INADDR_ANY) >> 8 & 0xFF; 90 | filler[6] = htonl(INADDR_ANY) >> 16 & 0xFF; 91 | filler[7] = htonl(INADDR_ANY) >> 24 & 0xFF; 92 | memcpy(&serv_addr, filler, sizeof(serv_addr)); 93 | */ 94 | 95 | /* 96 | * Note that we do not bind() our socket to any socket adddress here. 97 | * This is because on the client side, you would only use bind() if you want 98 | * to use a particular client side port to connect to the server. 99 | * When you do not bind(), the kernel will pick a port for you. 100 | * Read here how kernel gets you a port: https://idea.popcount.org/2014-04-03-bind-before-connect 101 | * There are a few protocols in the Unix world that expect clients to connect from a particular port. 102 | * Create a new socket address definition and bind it to socket in such cases: 103 | struct sockaddr_in client_addr; 104 | client_addr.sin_family = AF_INET; 105 | client_addr.sin_port = htons(CLIENT_PORT); 106 | client_addr.sin_addr.s_addr = htonl(INADDR_ANY); 107 | bind(sockfd, (struct sockaddr*) &client_addr, sizeof client_addr); 108 | */ 109 | 110 | /* makes connection per the socket address */ 111 | connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)); 112 | 113 | interact_with_server(sockfd); 114 | 115 | /* close socket since we are done */ 116 | close(sockfd); 117 | 118 | return 0; 119 | } 120 | -------------------------------------------------------------------------------- /basic/server.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Arjun Sreedharan 3 | * License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define BUFF_SIZE 256 14 | 15 | static unsigned short port = 55555; 16 | 17 | void serve_client(int cfd) 18 | { 19 | char buffer[BUFF_SIZE] = {0}; 20 | write(cfd, "You are now connected.\nEnter username:", 38); 21 | /* wait for username */ 22 | read(cfd, buffer, BUFF_SIZE); 23 | 24 | if(strcmp(buffer, "arjun024")) { 25 | write(cfd, "Authentication failed", 21); 26 | printf("A user tried to login using: %s\n", buffer); 27 | return; 28 | } 29 | write(cfd, "Authentication success", 22); 30 | printf("%s has logged in.\n", buffer); 31 | return; 32 | } 33 | 34 | int main(void) 35 | { 36 | int sockfd, client_sockfd; 37 | pid_t pid; 38 | 39 | /* 40 | * struct sockaddr defines a socket address. 41 | * A socket address is a combination of address family, 42 | * ip address and port. 43 | * For IP sockets, we may use struct sockaddr_in which is 44 | * just a wrapper around struct sockaddr. 45 | * Funtions like bind() etc are only aware of struct sockaddr. 46 | */ 47 | struct sockaddr_in serv_addr, client_addr; 48 | unsigned int supplied_len; 49 | unsigned int *ip_suppliedlen_op_storedlen; 50 | 51 | /* 52 | * creates a socket of family Internet sockets (AF_INET) and 53 | * of type stream. 0 indicates to system to choose appropriate 54 | * protocol (eg: TCP) 55 | */ 56 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 57 | 58 | /* 59 | * Socket adddress represented by struct sockaddr: 60 | * first 2 bytes: Address Family, 61 | * next 2 bytes: port, 62 | * next 4 bytes: ipaddr, 63 | * next 8 bytes: zeroes 64 | */ 65 | /* 66 | * htons() and htonl() change endianness to 67 | * network order which is the standard for network 68 | * communication. 69 | */ 70 | 71 | serv_addr.sin_family = AF_INET; 72 | serv_addr.sin_port = htons(port); 73 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 74 | 75 | /* 76 | * The above achieves what could be done using the following 77 | * on a little endian machine. 78 | * This breaks if the structure has padding 79 | char filler[16] = {0}; 80 | filler[0] = AF_INET & 0xFF; 81 | filler[1] = AF_INET >> 8 & 0xFF; 82 | filler[2] = htons(port) & 0xFF; 83 | filler[3] = htons(port) >> 8 & 0xFF; 84 | filler[4] = htonl(INADDR_ANY) & 0xFF; 85 | filler[5] = htonl(INADDR_ANY) >> 8 & 0xFF; 86 | filler[6] = htonl(INADDR_ANY) >> 16 & 0xFF; 87 | filler[7] = htonl(INADDR_ANY) >> 24 & 0xFF; 88 | memcpy(&serv_addr, filler, sizeof(serv_addr)); 89 | */ 90 | 91 | /* binds a socket to an address */ 92 | bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)); 93 | 94 | /* 95 | * allows the process to listen on the socket for given 96 | * max number of connections 97 | */ 98 | listen(sockfd, 5); 99 | 100 | /* 101 | * This ptr on input specifies the length of the supplied sockaddr, 102 | * and on output specifies the length of the stored address 103 | */ 104 | supplied_len = sizeof(client_addr); 105 | ip_suppliedlen_op_storedlen = &supplied_len; 106 | 107 | /* 108 | * ready to accept multiple clients - 109 | * for each client, we will fork and let the parent come back to 110 | * the beginning of the loop to wait for further clients 111 | * while the child deals with the accepted client. 112 | */ 113 | while(1) { 114 | /* 115 | * causes the process to block until a client connects to the server, 116 | * returns a new file descriptor to communicate with the connected client 117 | */ 118 | client_sockfd = accept(sockfd, (struct sockaddr*) &client_addr, 119 | ip_suppliedlen_op_storedlen); 120 | 121 | pid = fork(); 122 | 123 | if(pid > 0) { 124 | /* parent */ 125 | close(client_sockfd); 126 | continue; 127 | } 128 | 129 | if(pid == 0) { 130 | /* child */ 131 | close(sockfd); 132 | serve_client(client_sockfd); 133 | break; 134 | } 135 | } 136 | return 0; 137 | } 138 | -------------------------------------------------------------------------------- /bittorent/README: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arjun024/socketfun/bde980f02962562dde21b313407708aeddf5982b/bittorent/README -------------------------------------------------------------------------------- /chat/Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | 3 | CFLAGS = -lpthread -std=c90 -Wall 4 | 5 | SERVER_TARGET = chatserver 6 | CLIENT_TARGET = chatclient 7 | 8 | all: $(SERVER_TARGET) $(CLIENT_TARGET) 9 | 10 | $(SERVER_TARGET): $(SERVER_TARGET).c 11 | $(CC) $(CFLAGS) -o $(SERVER_TARGET) $(SERVER_TARGET).c 12 | 13 | $(CLIENT_TARGET): $(CLIENT_TARGET).c 14 | $(CC) $(CFLAGS) -o $(CLIENT_TARGET) $(CLIENT_TARGET).c 15 | 16 | clean: 17 | rm $(SERVER_TARGET) $(CLIENT_TARGET) 18 | -------------------------------------------------------------------------------- /chat/README: -------------------------------------------------------------------------------- 1 | socketfun - chat 2 | ---------------- 3 | 4 | This accomplishes a chat server and clients that can chat with each other. 5 | Error checking is not performed for purpose of brevity and readability. 6 | 7 | build instructions 8 | -------------------------- 9 | $ gcc -o chatserver -lpthread -std=c90 -Wall chatserver.c 10 | $ gcc -o chatclient -lpthread -std=c90 -Wall chatclient.c 11 | 12 | or do 13 | 14 | $ make 15 | 16 | running 17 | ------- 18 | $ ./chatserver 19 | 20 | On different teminals 21 | 22 | $ ./chatclient 23 | 24 | commands 25 | -------- 26 | ls - to get list of users currently connected to the server 27 | 28 | send - to send a message to a particular user 29 | 30 | exit - to disconnect from the server 31 | 32 | clean up 33 | -------- 34 | $ make clean 35 | -------------------------------------------------------------------------------- /chat/chatclient.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Arjun Sreedharan 3 | * License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #define BUFF_SIZE 256 15 | #define USERNAME_MAX_SIZE 20 16 | 17 | static unsigned short port = 55555; 18 | static char username[USERNAME_MAX_SIZE]; 19 | 20 | /* 21 | * Conditional variables (@console_cv) permit us to wait until 22 | * another thread completes an arbitrary activity. 23 | * A mutex (@console_cv_lock) is required to protect the condition 24 | * variable itself from race condition. 25 | */ 26 | pthread_cond_t console_cv; 27 | pthread_mutex_t console_cv_lock; 28 | 29 | void error(void) 30 | { 31 | fprintf(stderr, "%s\n", "bad command\n" 32 | "syntax: [command] [optional recipient] [optional msg]"); 33 | } 34 | 35 | void console(int sockfd) 36 | { 37 | char buffer[BUFF_SIZE]; 38 | char *recipient, *msg, *tmp; 39 | 40 | memset(buffer, 0, sizeof buffer); 41 | printf("%s\n%s\n", "Welcome to chat client console. Please enter commands", 42 | "syntax: [command] [optional recipient] [optional msg]"); 43 | 44 | /* 45 | * Issue the prompt and wait for command, 46 | * process the command and 47 | * repeat forever 48 | */ 49 | while(1) { 50 | /* console prompt */ 51 | printf("[%s]$ ", username); 52 | fgets(buffer, sizeof buffer, stdin); 53 | /* fgets also reads the \n from stdin, strip it */ 54 | buffer[strlen(buffer) - 1] = '\0'; 55 | 56 | if(strcmp(buffer, "") == 0) 57 | continue; 58 | 59 | if(strncmp(buffer, "exit", 4) == 0) { 60 | /* tell server to clean up structures for the client */ 61 | write(sockfd, "exit", 6); 62 | /* clean up self and exit */ 63 | pthread_mutex_destroy(&console_cv_lock); 64 | pthread_cond_destroy(&console_cv); 65 | _exit(EXIT_SUCCESS); 66 | } 67 | 68 | /* 69 | * `ls` is sent to server to get list of connected users. 70 | * It is written to server's socket, then using conditional wait, 71 | * we `wait` until the reply arrives in the receiver thread, where 72 | * `signal` is done immediately when the reply is read 73 | */ 74 | if(strncmp(buffer, "ls", 2) == 0) { 75 | /* 76 | * The mutex the protects the conditional has to 77 | * be locked before a conditional wait. 78 | */ 79 | pthread_mutex_lock(&console_cv_lock); 80 | write(sockfd, "ls", 2); 81 | /* not protected from spurious wakeups */ 82 | /* 83 | * This operation unlocks the given mutex and waits until a 84 | * pthread_cond_signal() happens on the same conditonal variable. 85 | * Then the given mutex is again unlocked 86 | */ 87 | pthread_cond_wait(&console_cv, &console_cv_lock); 88 | /* release the mutex */ 89 | pthread_mutex_unlock(&console_cv_lock); 90 | continue; 91 | } 92 | 93 | /* `send ` sends to the given */ 94 | if(strncmp(buffer, "send ", 5) == 0) { 95 | /* the following is to validate the syntax */ 96 | tmp = strchr(buffer, ' '); 97 | if(tmp == NULL) { 98 | error(); 99 | continue; 100 | } 101 | recipient = tmp + 1; 102 | 103 | tmp = strchr(recipient, ' '); 104 | if(tmp == NULL) { 105 | error(); 106 | continue; 107 | } 108 | msg = tmp + 1; 109 | 110 | /* issue the `send` command to server */ 111 | write(sockfd, buffer, 5 + strlen(recipient) + 1 + strlen(msg) + 1); 112 | continue; 113 | } 114 | 115 | error(); 116 | } 117 | } 118 | 119 | /* 120 | * write username to server 121 | * in the syntax: register username 122 | */ 123 | void register_username(int sockfd) 124 | { 125 | char *regstring = malloc(USERNAME_MAX_SIZE + 18); 126 | sprintf(regstring, "register username %s", username); 127 | write(sockfd, regstring, strlen(regstring)); 128 | free(regstring); 129 | } 130 | 131 | /* 132 | * the stupid receiver thread 133 | * It continuously waits for messages from the server, 134 | * and prints it whatever it is. 135 | */ 136 | void *receiver(void *sfd) 137 | { 138 | char buffer[BUFF_SIZE] = {0}; 139 | int sockfd = *(int*)sfd; 140 | int readlen; 141 | /* 142 | * If a new msg is received when we are processing the prev msg, 143 | * the kernel buffers the received data for us since we use streaming sockets. 144 | * It waits in queue until the next read(). 145 | * That's the reason we do not create a thread for every received msg. 146 | */ 147 | while(1) { 148 | memset(buffer, 0, sizeof buffer); 149 | readlen = read(sockfd, buffer, sizeof buffer); 150 | if(readlen < 1) 151 | continue; 152 | pthread_mutex_lock(&console_cv_lock); 153 | printf("%s\n", buffer); 154 | /* let the other thread stop waiting, if it is */ 155 | pthread_cond_signal(&console_cv); 156 | pthread_mutex_unlock(&console_cv_lock); 157 | } 158 | } 159 | 160 | int main(void) 161 | { 162 | int sockfd; 163 | 164 | /* 165 | * struct sockaddr defines a socket address. 166 | * A socket address is a combination of address family, 167 | * ip address and port. 168 | * For IP sockets, we may use struct sockaddr_in which is 169 | * just a wrapper around struct sockaddr. 170 | * Funtions like bind() etc are only aware of struct sockaddr. 171 | */ 172 | struct sockaddr_in serv_addr; 173 | 174 | /* just to dump the handle for the spawned thread - no use */ 175 | pthread_t receiver_thread; 176 | 177 | pthread_cond_init(&console_cv, NULL); 178 | pthread_mutex_init(&console_cv_lock, NULL); 179 | 180 | /* 181 | * creates a socket of family Internet sockets (AF_INET) and 182 | * of type stream. 0 indicates to system to choose appropriate 183 | * protocol (eg: TCP) 184 | */ 185 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 186 | 187 | /* 188 | * Socket adddress represented by struct sockaddr: 189 | * first 2 bytes: Address Family, 190 | * next 2 bytes: port, 191 | * next 4 bytes: ipaddr, 192 | * next 8 bytes: zeroes 193 | */ 194 | /* 195 | * htons() and htonl() change endianness to 196 | * network order which is the standard for network 197 | * communication. 198 | */ 199 | 200 | serv_addr.sin_family = AF_INET; 201 | serv_addr.sin_port = htons(port); 202 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 203 | 204 | /* 205 | * The above achieves what could be done using the following 206 | * on a little endian machine. 207 | * This breaks if the structure has padding 208 | char filler[16] = {0}; 209 | filler[0] = AF_INET & 0xFF; 210 | filler[1] = AF_INET >> 8 & 0xFF; 211 | filler[2] = htons(port) & 0xFF; 212 | filler[3] = htons(port) >> 8 & 0xFF; 213 | filler[4] = htonl(INADDR_ANY) & 0xFF; 214 | filler[5] = htonl(INADDR_ANY) >> 8 & 0xFF; 215 | filler[6] = htonl(INADDR_ANY) >> 16 & 0xFF; 216 | filler[7] = htonl(INADDR_ANY) >> 24 & 0xFF; 217 | memcpy(&serv_addr, filler, sizeof(serv_addr)); 218 | */ 219 | 220 | /* 221 | * Note that we do not bind() our socket to any socket adddress here. 222 | * This is because on the client side, you would only use bind() if you want 223 | * to use a particular client side port to connect to the server. 224 | * When you do not bind(), the kernel will pick a port for you. 225 | * Read here how kernel gets you a port: https://idea.popcount.org/2014-04-03-bind-before-connect 226 | * There are a few protocols in the Unix world that expect clients to connect from a particular port. 227 | * Create a new socket address definition and bind it to socket in such cases: 228 | struct sockaddr_in client_addr; 229 | client_addr.sin_family = AF_INET; 230 | client_addr.sin_port = htons(CLIENT_PORT); 231 | client_addr.sin_addr.s_addr = htonl(INADDR_ANY); 232 | bind(sockfd, (struct sockaddr*) &client_addr, sizeof client_addr); 233 | */ 234 | 235 | /* makes connection per the socket address */ 236 | connect(sockfd, (struct sockaddr*) &serv_addr, sizeof serv_addr); 237 | 238 | printf("%s\n", "Enter a username (max 20 characters, no spaces):"); 239 | fgets(username, sizeof username, stdin); 240 | /* fgets also reads the \n from stdin, strip it */ 241 | username[strlen(username) - 1] = '\0'; 242 | 243 | register_username(sockfd); 244 | /* spawn a new thread that continuously listens for any msgs from server */ 245 | pthread_create(&receiver_thread, NULL, receiver, (void*)&sockfd); 246 | /* get our console in action, let the user enter commands */ 247 | console(sockfd); 248 | 249 | return 0; 250 | } 251 | -------------------------------------------------------------------------------- /chat/chatserver.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Arjun Sreedharan 3 | * License: GPL version 2 or higher http://www.gnu.org/licenses/gpl.html 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #define BUFF_SIZE 256 15 | #define USERNAME_MAX_SIZE 20 16 | 17 | static unsigned short port = 55555; 18 | 19 | /* client_node abstracts a connected client */ 20 | struct client_node { 21 | int sockfd; 22 | char username[USERNAME_MAX_SIZE]; 23 | struct client_node *next; 24 | }; 25 | 26 | /* 27 | * a list of `client_node`s which serves as our 28 | * connected client list 29 | */ 30 | struct client_node *client_list = NULL; 31 | 32 | /* 33 | * any operation on the client list is to be performed 34 | * only after getting a lock on this mutex 35 | */ 36 | pthread_mutex_t client_list_lock; 37 | 38 | /* add to the linked list - no rocket science */ 39 | struct client_node *add_client(int cfd) 40 | { 41 | struct client_node *p = client_list; 42 | struct client_node *c = malloc(sizeof(struct client_node)); 43 | c->sockfd = cfd; 44 | c->username[0] = '\0'; 45 | c->next = NULL; 46 | /* always get a lock before you mess with list */ 47 | pthread_mutex_lock(&client_list_lock); 48 | while(p && p->next) 49 | p = p->next; 50 | if(p == NULL) 51 | client_list = c; 52 | else 53 | p->next = c; 54 | /* release the lock when we are done with */ 55 | pthread_mutex_unlock(&client_list_lock); 56 | return c; 57 | } 58 | 59 | /* 60 | * return NULL if no node is present with username @recipient, 61 | * else return pointer to the node 62 | */ 63 | struct client_node *search_client_list(char *recipient) 64 | { 65 | struct client_node *p = client_list; 66 | if(recipient == NULL || *recipient == '\0') 67 | return NULL; 68 | /* I am a law abiding citizen, wait until I get a lock */ 69 | pthread_mutex_lock(&client_list_lock); 70 | while(p != NULL) { 71 | if(strcmp(p->username, recipient) == 0) { 72 | /* never forget to release the lock, don't you like freedom */ 73 | pthread_mutex_unlock(&client_list_lock); 74 | return p; 75 | } 76 | p = p->next; 77 | } 78 | pthread_mutex_unlock(&client_list_lock); 79 | return NULL; 80 | } 81 | 82 | /* remove the client fromt he list of clients */ 83 | void remove_client(struct client_node *c) 84 | { 85 | struct client_node *p, *prev; 86 | p = client_list; 87 | prev = NULL; 88 | /* get a lock and only then touch the list */ 89 | pthread_mutex_lock(&client_list_lock); 90 | if(p == c) { 91 | client_list = p->next; 92 | pthread_mutex_unlock(&client_list_lock); 93 | return; 94 | } 95 | while(p != c && p != NULL) { 96 | prev = p; 97 | p = p->next; 98 | } 99 | if(prev && p) 100 | prev->next = p->next; 101 | pthread_mutex_unlock(&client_list_lock); 102 | } 103 | 104 | char *get_username(struct client_node *cnode) 105 | { 106 | char *str = malloc(38); 107 | read(cnode->sockfd, str, 38); 108 | /* 109 | * gives pointer to the character after the second space, 110 | * assuming str to be "register username " 111 | */ 112 | return strrchr(str, ' ') + 1; 113 | } 114 | 115 | void *handle_client(void* c) 116 | { 117 | char buffer[BUFF_SIZE] = {0}; 118 | struct client_node *cnode, *targetnode, *tmpnode; 119 | char *recipient, *msg, *tmp, *formatted_msg; 120 | /* cast the void* pointer back to its original type */ 121 | cnode = (struct client_node *)c; 122 | 123 | /* 124 | * expecting client program's register_username() to send 125 | * a msg of syntax "register username " 126 | * This parsed by get_username() to retrieve username, 127 | * and then copied to the client's node. 128 | */ 129 | strcpy(cnode->username, get_username(cnode)); 130 | /* logging in the server */ 131 | printf("user: %s, socket: %d, thread:%lu\n", 132 | cnode->username, cnode->sockfd, (unsigned long)pthread_self()); 133 | 134 | /* 135 | * read each `instruction` from the client, 136 | * take approprite action, and then come back to beginning 137 | * of the loop to wait for further instructions 138 | */ 139 | while(1) { 140 | memset(buffer, 0, sizeof buffer); 141 | /* read() call blocks till receipt of a msg */ 142 | read(cnode->sockfd, buffer, sizeof buffer); 143 | 144 | if(strncmp(buffer, "exit", 4) == 0) { 145 | /* clean up when a client quits */ 146 | remove_client(cnode); 147 | close(cnode->sockfd); 148 | free(cnode); 149 | } 150 | 151 | /* 152 | * `ls` lists all clients' usernames that are 153 | * currently connected 154 | */ 155 | if(strncmp(buffer, "ls", 2) == 0) { 156 | memset(buffer, 0, sizeof buffer); 157 | tmpnode = client_list; 158 | while(tmpnode) { 159 | /* concatenate each username to the buffer */ 160 | strcat(buffer, tmpnode->username); 161 | strcat(buffer, "\n"); 162 | tmpnode = tmpnode->next; 163 | } 164 | /* write the buffer to cient's socket */ 165 | write(cnode->sockfd, buffer, strlen(buffer)); 166 | } 167 | 168 | /* `send ` sends to the given */ 169 | if(strncmp(buffer, "send ", 5) == 0) { 170 | /* parse buffer to separate recipient and msg */ 171 | tmp = strchr(buffer, ' '); 172 | if(tmp == NULL) 173 | continue; 174 | recipient = tmp + 1; 175 | 176 | tmp = strchr(recipient, ' '); 177 | if(tmp == NULL) 178 | continue; 179 | *tmp = '\0'; 180 | msg = tmp + 1; 181 | 182 | /* search for the recipient in the cient list */ 183 | targetnode = search_client_list(recipient); 184 | 185 | /* on invalid recipient, do nothing */ 186 | if(targetnode == NULL) 187 | continue; 188 | 189 | formatted_msg = malloc(BUFF_SIZE); 190 | /* sprint is notorious for buffer overflow */ 191 | if(BUFF_SIZE < strlen(cnode->username) + strlen(msg) + 2) 192 | continue; 193 | /* create a string of syntax `: ` to send to recipient */ 194 | sprintf(formatted_msg, "%s: %s", cnode->username, msg); 195 | /* logging in the server */ 196 | printf("%s sent msg to %s\n", cnode->username, targetnode->username); 197 | /* Hey target client, You've got message ;) */ 198 | write(targetnode->sockfd, formatted_msg, strlen(formatted_msg) + 1); 199 | free(formatted_msg); 200 | } 201 | } 202 | 203 | /* 204 | * clean up 205 | * Let me tell you a secret, this never happens 206 | * Oh, wait !! 207 | */ 208 | pthread_mutex_destroy(&client_list_lock); 209 | close(cnode->sockfd); 210 | return NULL; 211 | } 212 | 213 | int main(void) 214 | { 215 | int sockfd, client_sockfd; 216 | 217 | /* 218 | * struct sockaddr defines a socket address. 219 | * A socket address is a combination of address family, 220 | * ip address and port. 221 | * For IP sockets, we may use struct sockaddr_in which is 222 | * just a wrapper around struct sockaddr. 223 | * Funtions like bind() etc are only aware of struct sockaddr. 224 | */ 225 | struct sockaddr_in serv_addr, client_addr; 226 | unsigned int supplied_len; 227 | unsigned int *ip_suppliedlen_op_storedlen; 228 | 229 | /* just to dump the handle for the spawned thread - no use */ 230 | pthread_t thread; 231 | 232 | /* 233 | * initiate a mutex to protect the client list from 234 | * being accessed by multiple threads at the same time 235 | */ 236 | pthread_mutex_init(&client_list_lock, NULL); 237 | 238 | /* 239 | * creates a socket of family Internet sockets (AF_INET) and 240 | * of type stream. 0 indicates to system to choose appropriate 241 | * protocol (eg: TCP) 242 | */ 243 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 244 | 245 | /* 246 | * Socket adddress represented by struct sockaddr: 247 | * first 2 bytes: Address Family, 248 | * next 2 bytes: port, 249 | * next 4 bytes: ipaddr, 250 | * next 8 bytes: zeroes 251 | */ 252 | /* 253 | * htons() and htonl() change endianness to 254 | * network order which is the standard for network 255 | * communication. 256 | */ 257 | 258 | serv_addr.sin_family = AF_INET; 259 | serv_addr.sin_port = htons(port); 260 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 261 | 262 | /* 263 | * The above achieves what could be done using the following 264 | * on a little endian machine. 265 | * This breaks if the structure has padding 266 | char filler[16] = {0}; 267 | filler[0] = AF_INET & 0xFF; 268 | filler[1] = AF_INET >> 8 & 0xFF; 269 | filler[2] = htons(port) & 0xFF; 270 | filler[3] = htons(port) >> 8 & 0xFF; 271 | filler[4] = htonl(INADDR_ANY) & 0xFF; 272 | filler[5] = htonl(INADDR_ANY) >> 8 & 0xFF; 273 | filler[6] = htonl(INADDR_ANY) >> 16 & 0xFF; 274 | filler[7] = htonl(INADDR_ANY) >> 24 & 0xFF; 275 | memcpy(&serv_addr, filler, sizeof(serv_addr)); 276 | */ 277 | 278 | /* binds a socket to an address */ 279 | bind(sockfd, (struct sockaddr*) &serv_addr, sizeof serv_addr); 280 | 281 | /* 282 | * allows the process to listen on the socket for given 283 | * max number of connections 284 | */ 285 | listen(sockfd, 5); 286 | 287 | /* 288 | * This ptr on input specifies the length of the supplied sockaddr, 289 | * and on output specifies the length of the stored address 290 | */ 291 | supplied_len = sizeof(client_addr); 292 | ip_suppliedlen_op_storedlen = &supplied_len; 293 | 294 | /* 295 | * Now ready to accept clients - 296 | * For each client, a new client_node is created and added to the client list. 297 | * To handle the client, a new thread is spawned handled by handle_client(). 298 | * Then, we let the main thread come back to the beginning of the loop to wait for 299 | * further clients while the newly spawned thread deals with the accepted client. 300 | */ 301 | while(1) { 302 | struct client_node *cnode; 303 | /* 304 | * causes the process to block until a client connects to the server, 305 | * returns a new file descriptor to communicate with the connected client 306 | */ 307 | client_sockfd = accept(sockfd, (struct sockaddr*) &client_addr, 308 | ip_suppliedlen_op_storedlen); 309 | 310 | cnode = add_client(client_sockfd); 311 | 312 | /* pass a pointer to the correspond client node to the new thread's handler */ 313 | pthread_create(&thread, NULL, handle_client, (void*)cnode); 314 | } 315 | return 0; 316 | } 317 | -------------------------------------------------------------------------------- /p2p/README: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arjun024/socketfun/bde980f02962562dde21b313407708aeddf5982b/p2p/README --------------------------------------------------------------------------------