Book Image

Hands-On Network Programming with C

By : Lewis Van Winkle
Book Image

Hands-On Network Programming with C

By: Lewis Van Winkle

Overview of this book

Network programming enables processes to communicate with each other over a computer network, but it is a complex task that requires programming with multiple libraries and protocols. With its support for third-party libraries and structured documentation, C is an ideal language to write network programs. Complete with step-by-step explanations of essential concepts and practical examples, this C network programming book begins with the fundamentals of Internet Protocol, TCP, and UDP. You’ll explore client-server and peer-to-peer models for information sharing and connectivity with remote computers. The book will also cover HTTP and HTTPS for communicating between your browser and website, and delve into hostname resolution with DNS, which is crucial to the functioning of the modern web. As you advance, you’ll gain insights into asynchronous socket programming and streams, and explore debugging and error handling. Finally, you’ll study network monitoring and implement security best practices. By the end of this book, you’ll have experience of working with client-server applications and be able to implement new network programs in C. The code in this book is compatible with the older C99 version as well as the latest C18 and C++17 standards. You’ll work with robust, reliable, and secure code that is portable across operating systems, including Winsock sockets for Windows and POSIX sockets for Linux and macOS.
Table of Contents (26 chapters)
Title Page
Dedication
About Packt
Contributors
Preface
Index

The main loop


With our many helper functions out of the way, we can now finish web_server.c. Remember to first #include chap07.h and also add in all of the types and functions we've defined so far—struct client_info, get_content_type(), create_socket(), get_client(), drop_client(), get_client_address(), wait_on_clients(), send_400(), send_404(), and serve_resource().

We can then begin the main() function. It starts by initializing Winsock on Windows:

/*web_server.c except*/

int main() {

#if defined(_WIN32)
    WSADATA d;
    if (WSAStartup(MAKEWORD(2, 2), &d)) {
        fprintf(stderr, "Failed to initialize.\n");
        return 1;
    }
#endif

We then use our earlier function, create_socket(), to create the listening socket. Our server listens on port 8080, but feel free to change it. On Unix-based systems, listening on low port numbers is reserved for privileged accounts. For security reasons, our web server should be running with unprivileged accounts only. This is why we use 8080 as...