C programming networking windows

Программирование сетевых приложений (TCP/IP) на C/C++

Простейшие примеры

TCP/IP

Что следует иметь ввиду при разработке с TCP

  1. TCP не выполняет опрос соединения (не поможет даже keep alive — он нужен для уборки мусора, а не контроля за состоянием соединения). Исправляется на прикладном уровне, например, реализацией пульсации. Причем на дополнительном соединении.
  2. Задержки при падении хостов, разрыве связи.
  3. Необходимо следить за порядком получения сообщений.
  4. Заранее неизвестно сколько данных будет прочитано из сокета. Может быть прочитано несколько пакетов сразу!
  5. Надо быть готовым ко всем внештатным ситуациям:
    • постоянный или временный сбой сети
    • отказ принимающего приложения
    • аварийный сбой самого хоста на принимающей стороне
    • неверное поведение хоста на принимающей стороне
    • учитывать особенности сети функционирования приложения (глобальная или локальная)

OSI и TCP/IP

OSI TCP/IP
Прикладной уровень Прикладной уровень
Уровень представления
Сеансовый уровень Транспортный уровень
Транспортный уровень Межсетевой уровень
Сетевой уровень Интерфейсный уровень
Канальный уровень
Физический уровень

Порты

Порт Кем контроллируется
0 — 1023 Контролируется IANA
1024 — 49151 Регистрируется в IANA
49152 — 65535 Эфимерные

Полный список зарегистрированных портов расположен по адресу: http://www.isi.edu/in-notes/iana/assignment/port-numbers. Подать заявку на получение хорошо известного или зарегистрированного номера порта можно по адресу http://www.isi.edu/cgi-bin/iana/port-numbers.pl.

Состояние TIME-WAIT

После активного закрытия для данного конкретного соединения стек входит в состояние TIME-WAIT на время 2MSL (максимальное время жизни пакета) для того, чтобы

  1. заблудившийся пакет не попал в новое соединение с такими же параметрами.
  2. если потерялся ACK, подтверждающий закрытие соединения, с активной стороны, пассивная снова пощлёт FIN, активная, игнорируя TIME-WAIT уже закрыла соединение, поэтому пассивная сторона получит RST.

Отключение состояния TIME-WAIT крайне не рекомендуется, так как это нарушает безопасность TCP соединения, тем не менее существует возможность сделать это — опция сокета SO_LINGER.

Штатная ситуация — перезагрузка сервера может пострадать из-за наличия TIME-WAIT. Эта проблема решается заданием опции SO_REUSEADDR.

Отложенное подтверждение и алгоритм Нейгла.

Алгоритм Нейгла используется для предотвращения забивания сети мелкими пакетами и имеет очень простую формулировку — запрещено посылать второй маленький пакет до тех пор, пока не придет подтверждение на первый. Тем не менее данные отправляются при выполнении хотя бы одного из следующих условий:

  • можно послать полный сегмент размером MSS (максимальный размер сегмента)
  • соединение простаивает, и можно опустошить буфер передачи
  • алгоритм Нейгла отключен, и можно опустошить буфер передачи
  • есть срочные данные для отправки
  • есть маленьки сегмент, но его отправка уже задержана на достаточно длительное время (таймер терпения persist timer на тайм-аут ретрансмиссии RTO )
  • окно приема, объявленное хостом на другом конце, открыто не менее чем на половину
  • необходимо повторно передать сегмент
  • требуется послать ACK на принятые данные
  • нужно объявить об обновлении окна

Кроме того, существует отложенное подтверждение. При этом хост, получивший сегмент, старается задержать отправку ACK, чтобы послать её вместе с данными.

Алгоритм Нейгла в купе с отложенным подтверждением в резонансе дают нежелательные задержки. Поэтому часто его отключают. Отключение алгоритма Нейгла производится заданием опции TCP_NODELAY

Но более правильным было бы проектировать приложение таким образом, чтобы было как можно меньше маленьких блоков. Лучше писать большие. Для этого можно объединять данные самостоятельно, а можно пользоваться аналогом write, работающим с несколькими буферами:

Сетевое программирование в .NET Framework Network Programming in the .NET Framework

Microsoft .NET Framework обеспечивает многоуровневую, расширяемую и управляемую реализацию служб Интернета, которую можно легко и быстро интегрировать в приложения. The Microsoft .NET Framework provides a layered, extensible, and managed implementation of Internet services that can be quickly and easily integrated into your applications. В сетевых приложениях можно использовать подключаемые протоколы, которые позволяют автоматически применять новые протоколы Интернета, или управляемую реализацию интерфейса сокетов Windows, дающую возможность работать с сетью на уровне сокетов. Your network applications can build on pluggable protocols to automatically take advantage of new Internet protocols, or they can use a managed implementation of the Windows socket interface to work with the network on the socket level.

В этом разделе In This Section

Введение в подключаемые протоколы Introducing Pluggable Protocols
Описание способов доступа к интернет-ресурсу вне зависимости от используемого протокола доступа Describes how to access an Internet resource without regard to the access protocol that it requires.

Запрос данных Requesting Data
Объясняется, как использовать подключаемые протоколы для отправки и приема данных из интернет-ресурсов. Explains how to use pluggable protocols to upload and download data from Internet resources.

Программирование подключаемых протоколов Programming Pluggable Protocols
Объясняется, как создать классы для определенных протоколов чтобы реализовать подключаемые протоколы. Explains how to derive protocol-specific classes to implement pluggable protocols.

Использование протоколов приложений Using Application Protocols
Описание процесса создания приложений, которые используют сетевые протоколы, такие как TCP, UDP и HTTP. Describes programming applications that take advantage of network protocols such as TCP, UDP, and HTTP.

Протокол IP версии 6 Internet Protocol Version 6
Описание преимуществ протокола IP версии 6 (IPv6) над текущей версией набора протоколов IP (IPv4); описание адресации, маршрутизации и автоматической настройки IPv6, а также процедур включения и выключения IPv6. Describes the advantages of Internet Protocol version 6 (IPv6) over the current version of the Internet Protocol suite (IPv4), describes IPv6 addressing, routing and auto-configuration, and how to enable and disable IPv6.

Настройка веб-приложений Configuring Internet Applications
Описание использования файлов конфигурации .NET Framework для настройки интернет-приложений. Explains how to use the .NET Framework configuration files to configure Internet applications.

Трассировка сети в .NET Framework Network Tracing in the .NET Framework
Описание использования трассировки сети для получения сведений о вызовах методов и о сетевом трафике, созданном управляемым приложением. Explains how to use network tracing to get information about method invocations and network traffic generated by a managed application.

Безопасность в сетевом программировании Security in Network Programming
Описание использования стандартных методов безопасности и аутентификации в Интернете. Describes how to use standard Internet security and authentication techniques.

C programming networking windows

Hands-On Network Programming with C

This is the code repository for Hands-On Network Programming with C, written by Lewis Van Winkle and published by Packt.

Learn socket programming in C and write secure and optimized network code

What is this book about?

Network programming, a challenging topic in C, is made easy to understand with a careful exposition of socket programming APIs. This book gets you started with modern network programming in C and proper usage of the relevant operating system APIs.

This book covers the following exciting features:

  • Uncover cross-platform socket programming APIs
  • Implement techniques for supporting IPv4 and IPv6
  • Understand how TCP and UDP connections work over IP
  • Discover how hostname resolution and DNS work
  • Interface with web APIs using HTTP and HTTPS
  • Acquire hands-on experience with the email protocol (SMTP)
  • Gain real-world expertise with practical network applications
  • Explore new approaches for the Internet of Things (IoT)

If you feel this book is for you, get your copy today!

Instructions and Navigations

This repo contains the code which accompanies the book «Hands-On Network Programming with C», written by Lewis Van Winkle. The code is released under the MIT license.

Unless otherwise noted, all programs will compile cleanly on Windows, Linux, and macOS, and as C or C++. Code is tested with MinGW and Visual Studio on Windows, gcc and clang on Linux and macOS.

  • chap01/win_init.c Example code to initialize Winsock. (Windows only)
  • chap01/win_list.c List all local IP addresses. (Windows only)
  • chap01/unix_list.c List all local IP addresses. (Linux and macOS only)
  • chap02/sock_init.c Example program to include all needed headers and initialize.
  • chap02/time_console.c Prints to console the current date and time.
  • chap02/time_server.c Serves a web page giving current date and time.
  • chap02/time_server_ipv6.c As above, but listening for IPv6 connections.
  • chap02/time_server_dual.c As above, but listening for IPv6/IPv4 dual stack connections.
  • chap03/tcp_client.c Establish TCP connection and send/receive data from the console.
  • chap03/tcp_serve_toupper.c TCP server servicing multiple connections using select() . Echos received data back to client in all upper-case.
  • chap03/tcp_serve_toupper_fork.c As above, but uses fork() instead of select() . (Linux and macOS only)
  • chap03/tcp_serve_chat.c TCP server which relays received data to every other connected client.
  • chap04/udp_client.c Send/receive UDP data from the console.
  • chap04/udp_recvfrom.c Uses recvfrom() to receive one UDP packet.
  • chap04/udp_sendto.c Uses sendto() to send one UDP packet.
  • chap04/udp_serve_toupper.c Receives UDP data, and echos it back to the sender in all upper-case.
  • chap04/udp_serve_toupper_simple.c As above, but doesn’t use select() .
  • chap05/lookup.c Uses getaddrinfo() to lookup addresses for a given hostname.
  • chap05/dns_query.c Encodes and sends a DNS query, then decodes the response.
  • chap06/web_get.c A minimal HTTP client which will download a web resource from a given URL.
  • chap07/web_server.c A minimal web server.
  • chap07/web_server2.c A minimal web server (no globals).
  • chap08/smtp_send.c A simple email sender.

The examples in this chapter use OpenSSL. Be sure to link against the OpenSSL libraries when compiling ( -lssl -lcrypto ).

  • chap09/openssl_version.c A program to report the installed OpenSSL version.
  • chap09/https_simple.c A minimal program that requests a web page using HTTPS.
  • chap09/https_get.c The HTTP client of chapter 6 modified to use HTTPS.
  • chap09/tls_client.c The TCP client program of chapter 3 modified to use TLS/SSL.
  • chap09/tls_get_cert.c Prints a certificate from a TLS/SSL server.

The examples in this chapter use OpenSSL. Be sure to link against the OpenSSL libraries when compiling ( -lssl -lcrypto ).

  • chap10/tls_time_server.c The time server of chapter 2 modified to use HTTPS.
  • chap10/https_server.c The web server of chapter 7 modified to use HTTPS.

The examples in this chapter use libssh. Be sure to link against the libssh libraries when compiling ( -lssh ).

  • chap11/ssh_version.c A program to report the libssh version.
  • chap11/ssh_connect.c A minimal client that establishes a ssh connection.
  • chap11/ssh_auth.c A client which attempts authentication.
  • chap11/ssh_command.c A client that runs a single command over ssh.
  • chap11/ssh_download.c A client that downloads a file over ssh.

This chapter doesn’t include any example programs.

  • chap13/connect_timeout.c Shows how to timeout a connect() call early.
  • chap13/connect_blocking.c For comparison with connect_timeout.c.
  • chap13/server_reuse.c Demonstrates the use of SO_REUSEADDR .
  • chap13/server_noreuse.c For comparison with server_reuse.c.
  • chap13/server_crash.c This server purposefully writes to a TCP socket after the client disconnects.
  • chap13/error_text.c Shows how to obtain error code descriptions.
  • chap13/big_send.c TCP client. Sends lots of data after connecting. Used to show blocking behaviour of send() .
  • chap13/server_ignore.c TCP server. Accepts connections, then simply ignores them. Used to show blocking behaviour of send() .
  • chap13/setsize.c Shows max number of sockets select() can handle.

This chapter doesn’t include any example programs.

Following along with the code in this book requires that you to have access to a C compiler on a standard operating system. The example programs in this book were carefully tested on Windows, Linux, and macOS. They were tested using the gcc, clang, and Microsoft Visual Studio compilers. All of the code in this book will compile as either C or C++.

In addition, the code examples in Chapter 9, Loading Secure Web Pages with HTTPS and OpenSSL, and Chapter 10, Implementing a Secure Web Server, require that you have the OpenSSL library installed.

Chapter 11, Establishing SSH Connections with libssh, requires that the libssh library is installed.

Instructions for installing all of the require software are provided in the the appendices. See Appendix B, Setting Up Your C Compiler On Windows, Appendix C, Setting Up Your C Compiler On Linux, and Appendix D, Setting Up Your C Compiler On macOS, for compiler setup. A complete list of the example programs provided is given in Appendix E, Example Programs.

No non-free software is required to follow along with any of the examples in this book.

Get to Know the Author

Lewis Van Winkle is a software programming consultant, entrepreneur, and founder of a successful IoT company. He has over 20 years of programming experience after publishing his first successful software product at age twelve. He has over 15 years of programming experience with the C programming language on a variety of operating systems and platforms. He is active in the open-source community and has published several popular open-source programs and libraries, many of them in C. Today, Lewis spends much of his time consulting, where he loves taking on difficult projects that other programmers have given up on. He specializes in network systems, financial systems, machine learning, and interoperation between different programming languages.

Suggestions and Feedback

Please contact me if you have any feedback or suggestions.

Читайте также:  Не работает планшет после обновления windows
Оцените статью