Какая библиотека используется для работы с сокетами

от admin

Начинающему сетевому программисту

Тема сетевого программирования является для разработчиков одной из важнейших в современном цифровом мире. Правда, надо признать, что большая часть сетевого программирования сосредоточена в области написания скриптов исполнения для web-серверов на языках PHP, Python и им подобных. Как следствие — по тематике взаимодействия клиент-сервер при работе с web-серверами написаны терабайты текстов в Интернете. Однако когда я решил посмотреть, что же имеется в Интернете по вопросу программирования сетевых приложений с использованием голых сокетов, то обнаружил интересную вещь: да, такие примеры конечно же есть, но подавляющее большинство написано под *nix-системы с использованием стандартных библиотек (что понятно – в области сетевого программирования Microsoft играет роль сильно отстающего и менее надежного «собрата» *nix-ов). Другими словами все эти примеры просто не будут работать под Windows. При определенных танцах с бубнами код сетевого приложения под Linux можно запустить и под Windows, однако это еще более запутает начинающего программиста, на которого и нацелены большинство статей в Интернете с примерами использования сокетов.

Ну а что же с документацией по работе с сетевыми сокетами в Windows от самой Microsoft? Парадоксальность ситуации заключается в том, что непосредственно в самой документации приведено очень беглое описание функций и их использования, а в примерах имеются ошибки и вызовы старых «запрещенных» современными компиляторами функций (к примеру, функция inet_addr() — https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-listen ) — такие функции конечно же можно вызывать, заглушив бдительность компилятора через #define-директивы, однако такой подход является полным зашкваром для любого даже начинающего программиста и категорически не рекомендуется к использованию. Более того, фрагмент кода в примере от Microsoft по ссылке выше:

вообще не заработает, т.к. полю Service.sin_addr.s_addr невозможно присвоить значение целого типа, которое возвращает функция inet_addr (возвращает unsigned long). То есть это ни много, ни мало — ошибка! Можно себе представить, сколько пытливых бойцов полегло на этом месте кода.

В общем, посмотрев на всё это, я решил написать базовую статью по созданию простейшего клиент-сервер приложения на С++ под Windows с детальным описанием всех используемых функций. Это приложение будет использовать Win32API и делать незамысловатую вещь, а именно: передавать сообщения от клиента к серверу и обратно, или, иначе говоря – напишем программу по реализации чата для двух пользователей.

Сразу оговорюсь, что статья рассчитана на начинающих программистов, которые только входят в сетевое программирование под Windows. Необходимые навыки – базовое знание С++, а также теоретическая подготовка по теме сетевых сокетов и стека технологии TCP/IP.

Теория сокетов за 30 секунд для «dummies»

Начну всё-таки немного с теории в стиле «for dummies». В любой современной операционной системе, все процессы инкапсулируются, т.е. скрываются друг от друга, и не имеют доступа к ресурсам друг друга. Однако существуют специальные разрешенные способы взаимодействия процессов между собой. Все эти способы взаимодействия процессов можно разделить на 3 группы: (1) сигнальные, (2) канальные и (3) разделяемая память.

Когда мы говорим про работу сетевого приложения, то всегда подразумеваем взаимодействие процессов: процесс 1 (клиент) пытается что-то послать или получить от Процесса 2 (сервер). Наиболее простым и понятным способом организации сетевого взаимодействия процессов является построение канала между этими процессами. Именно таким путём и пошли разработчики первых сетевых протоколов. Получившийся способ взаимодействия сетевых процессов в итоге оказался многоуровневым: основной программный уровень — стек сетевой технологии TCP/IP, который позволяет организовать эффективную доставку пакетов информации между различными машинами в сети, а уже на прикладном уровне тот самый «сокет» позволяет разобраться какой пакет какому процессу доставить на конкретной машине.

Иными словами «сокет» — это «розетка» конкретного процесса, в которую надо подключиться, чтобы этому процессу передать какую-либо информацию. Договорились, что эта «розетка» в Сети описывается двумя параметрами – IP-адресом (для нахождения машины в сети) и Портом подключения (для нахождения процесса-адресата на конкретной машине).

Для того, чтобы сокеты заработали под Windows, необходимо при написании программы пройти следующие Этапы:

Инициализация сокетных интерфейсов Win32API.

Инициализация сокета, т.е. создание специальной структуры данных и её инициализация вызовом функции.

«Привязка» созданного сокета к конкретной паре IP-адрес/Порт – с этого момента данный сокет (его имя) будет ассоциироваться с конкретным процессом, который «висит» по указанному адресу и порту.

Для серверной части приложения: запуск процедуры «прослушки» подключений на привязанный сокет.

Для клиентской части приложения: запуск процедуры подключения к серверному сокету (должны знать его IP-адрес/Порт).

Акцепт / Подтверждение подключения (обычно на стороне сервера).

Обмен данными между процессами через установленное сокетное соединение.

Закрытие сокетного соединения.

Итак, попытаемся реализовать последовательность Этапов, указанных выше, для организации простейшего чата между клиентом и сервером. Запускаем Visual Studio, выбираем создание консольного проекта на С++ и поехали.

Этап 0: Подключение всех необходимых библиотек Win32API для работы с сокетами

Сокеты не являются «стандартными» инструментами разработки, поэтому для их активизации необходимо подключить ряд библиотек через заголовочные файлы, а именно:

WinSock2.h – заголовочный файл, содержащий актуальные реализации функций для работы с сокетами.

WS2tcpip.h – заголовочный файл, который содержит различные программные интерфейсы, связанные с работой протокола TCP/IP (переводы различных данных в формат, понимаемый протоколом и т.д.).

Также нам потребуется прилинковать к приложению динамическую библиотеку ядра ОС: ws2_32.dll. Делаем это через директиву компилятору: #pragma comment(lib, “ws2_32.lib”)

Ну и в конце Этапа 0 подключаем стандартные заголовочные файлы iostream и stdio.h

Итого по завершению Этапа 0 в Серверной и Клиентской частях приложения имеем:

Обратите внимание: имя системной библиотеки ws2_32.lib именно такое, как это указано выше. В Сети есть различные варианты написания имени данной библиотеки, что, возможно, связано иным написанием в более ранних версиях ОС Windows. Если вы используете Windows 10, то данная библиотека называется именно ws2_32.lib и находится в стандартной папке ОС: C:/Windows/System32 (проверьте наличие библиотеки у себя, заменив расширение с “lib” на “dll”).

Этап 1: Инициализация сокетных интерфейсов Win32API

Прежде чем непосредственно создать объект сокет, необходимо «запустить» программные интерфейсы для работы с ними. Под Windows это делается в два шага следующим образом:

Нужно определить с какой версией сокетов мы работаем (какую версию понимает наша ОС) и

Запустить программный интерфейс сокетов в Win32API. Ну либо расстроить пользователя тем, что ему не удастся поработать с сокетами до обновления системных библиотек

Первый шаг делается с помощью создания структуры типа WSADATA , в которую автоматически в момент создания загружаются данные о версии сокетов, используемых ОС, а также иная связанная системная информация: WSADATA wsData;

Второй шаг – непосредственный вызов функции запуска сокетов с помощью WSAStartup() . Упрощённый прототип данной функции выглядит так:

int WSAStartup (WORD <запрашиваемая версия сокетов>, WSADATA* <указатель на структуру, хранящую текущую версию реализации сокетов>)

Первый аргумент функции – указание диапазона версий реализации сокетов, которые мы хотим использовать и которые должны быть типа WORD . Этот тип данных является внутренним типом Win32API и представляет собой двухбайтовое слово (аналог в С++: unsigned short ). Функция WSAStartup() просит вас передать ей именно WORD , а она уже разложит значение переменной внутри по следующему алгоритму: функция считает, что в старшем байте слова указана минимальная версия реализации сокетов, которую хочет использовать пользователь, а в младшем – максимальная. По состоянию на дату написания этой статьи (октябрь 2021 г.) актуальная версия реализации сокетов в Windows – 2. Соответственно, желательно передать и в старшем, и в младшем байте число 2. Для того, чтобы создать такую переменную типа WORD и передать в её старший и младший байты число 2, можно воспользоваться Win32API функцией MAKEWORD(2,2) .

Можно немного повыёживаться и вспомнить (или полистать MSDN), что функция MAKEWORD(x,y) строит слово по правилу y << 8 | x .Нетрудно посчитать, что при x=y=2 значение функции MAKEWORD в десятичном виде будет 514 . Можешь смело передать в WSAStartup() это значение, и всё будет работать.

Второй аргумент функции – просто указатель на структуру WSADATA , которую мы создали ранее и в которую подгрузилась информация о текущей версии реализации сокетов на данной машине.

WSAStartup() в случае успеха возвращает 0, а в случае каких-то проблем возвращает код ошибки, который можно расшифровать последующим вызовом функции WSAGetLastError() .

Важное замечание: поскольку сетевые каналы связи и протоколы в теории считаются ненадежными (это отдельный большой разговор), то критически важно для сетевого приложения анализировать все возможные ошибки, которые возникают в процессе вызовов сокетных функций. По этой причине каждый вызов таких функций мы будем анализировать на ошибки и в случае их обнаружения завершать сетевые сеансы и закрывать открытые сокеты. Используем для этого переменную erStat типа int .

Также важно после работы приложения обязательно закрыть использовавшиеся сокеты с помощью функции closesocket(SOCKET <имя сокета>) и деинициализировать сокеты Win32API через вызов метода WSACleanup() .

Итого код Этапа 1 следующий:

Да, кода мало, а описания много. Так обычно и бывает, когда хочешь глубоко в чем-то разобраться. Так что на лабе будешь в первых рядах.

Этап 2: Создание сокета и его инициализация

Сокет в С++ – это структура данных (не класс) типа SOCKET. Её инициализация проводится через вызов функции socket() , которая привязывает созданный сокет к заданной параметрами транспортной инфраструктуре сети. Выглядит прототип данной функции следующим образом:

SOCKET socket(int <семейство используемых адресов>, int <тип сокета>, int <тип протокола>)

Семейство адресов: сокеты могут работать с большим семейством адресов. Наиболее частое семейство – IPv4. Указывается как AF_INET .

Тип сокета: обычно задается тип транспортного протокола TCP ( SOCK_STREAM ) или UDP ( SOCK_DGRAM ). Но бывают и так называемые «сырые» сокеты, функционал которых сам программист определяет в процессе использования. Тип обозначается SOCK_RAW

Тип протокола: необязательный параметр, если тип сокета указан как TCP или UDP – можно передать значение 0. Тут более детально останавливаться не будем, т.к. в 95% случаев используются типы сокетов TCP/UDP.

При необходимости подробно почитать про функцию socket() можно здесь.

Функция socket() возвращает дескриптор с номером сокета, под которым он зарегистрирован в ОС. Если же инициализировать сокет по каким-то причинам не удалось – возвращается значение INVALID_SOCKET .

Код Этапа 2 будет выглядеть так:

Этап 3: Привязка сокета к паре IP-адрес/Порт

Сокет уже существует, но еще неполноценный, т.к. ему не назначен внешний адрес, по которому его будут находить транспортные протоколы по заданию подключающихся процессов, а также не назначен порт, по которому эти подключающиеся процессы будут идентифицировать процесс-получатель.

Такое назначение делается с помощью функции bind() , имеющей следующий прототип:

int bind(SOCKET <имя сокета, к которому необходимо привязать адрес и порт>, sockaddr* <указатель на структуру, содержащую детальную информацию по адресу и порту, к которому надо привязать сокет>, int <размер структуры, содержащей адрес и порт>)

Функция bind() возвращает 0 , если удалось успешно привязать сокет к адресу и порту, и код ошибки в ином случае, который можно расшифровать вызовом WSAGetLastError() — см. итоговый код Этапа 3 далее.

Тут надо немножно притормозить и разобраться в том, что за такая структура типа sockaddr передается вторым аргументом в функцию bind() . Она очень важна, но достаточно запутанная.

Итак, если посмотреть в её внутренности, то выглядят они очень просто: в ней всего два поля – (1) первое поле хранит семейство адресов, с которыми мы уже встречались выше при инициализации сокета, а (2) второе поле хранит некие упакованные последовательно и упорядоченные данные в размере 14-ти байт. Бессмысленно разбираться детально как именно эти данные упакованы, достаточно лишь понимать, что в этих 14-ти байтах указан и адрес, и порт, а также дополнительная служебная информация для других системных функций Win32API .

Но как же явно указать адрес и порт для привязки сокета? Для этого нужно воспользоваться другой структурой, родственной sockaddr , которая легко приводится к этому типу — структурой типа sockaddr_in .

В ней уже более понятные пользователю поля, а именно:

Семейство адресов — опять оно ( sin_family )

Вложенная структура типа in_addr , в которой будет храниться сам сетевой адрес ( sin_addr )

Технический массив на 8 байт ( sin_zero[8] )

При приведении типа sockaddr_in к нужному нам типу sockaddr для использования в функции bind() поля Порт (2 байта), Сетевой адрес (4 байта) и Технический массив (8 байт) как раз в сумме дают нам 14 байт, помещающихся в 14 байт, находящихся во втором поле структуры sockaddr . Первые поля у указанных типов совпадают – это семейство адресов сокетов (указываем AF_INET ). Из этого видно, что структуры данных типа sockaddr и sockaddr_in тождественны, содержат одну и ту же информацию, но в разной форме для разных целей.

Соответственно, ввод данных для структуры типа sockaddr_in выглядит следующим образом:

Создание структуры типа sockaddr_in : sockaddr_in servInfo;

Заполнение полей созданной структуры servInfo

servInfo.sin_port = htons(<указать номер порта как unsigned short>); порт всегда указывается через вызов функции htons() , которая переупаковывает привычное цифровое значение порта типа unsigned short в побайтовый порядок понятный для протокола TCP/IP (протоколом установлен порядок указания портов от старшего к младшему байту или «big-endian»).

Далее нам надо указать сетевой адрес для сокета. Тип этого поля – структура типа in_addr , которая по своей сути представляет просто особый «удобный» системным функциям вид обычного строчного IPv4 адреса. Таким образом, чтобы указать этому полю обычный IPv4 адрес, его нужно сначала преобразовать в особый числовой вид и поместить в структуру типа in_addr .

Благо существует функция, которая переводит обычную строку типа char[] , содержащую IPv4 адрес в привычном виде с точками-разделителями в структуру типа in_addr – функция inet_pton() . Прототип функции следующий:

int inet_pton(int <семейство адресов>, char[] <строка, содержащая IP-адрес в обычном виде с точкой-разделителем>, in_addr* <указатель на структуру типа in_addr, в которую нужно поместить результат приведения строчного адреса в численный>).

В случае ошибки функция возвращает значение меньше 0.

Соответственно, если мы хотим привязать сокет к локальному серверу, то наш код по преобразованию IPv4 адреса будет выглядеть так:

erStat = inet_pton(AF_INET, “127.0.0.1”, &ip_to_num);

cout << «Error in IP translation to special numeric format» << endl;

Результат перевода IP-адреса содержится в структуре ip_to_num. И далее мы передаем уже в нашу переменную типа sockaddr_in значение преобразованного адреса:

Вся нужная информация для привязки сокета теперь у нас есть, и она хранится в структуре servInfo . Можно смело вызывать функцию bind() , не забыв при этом привести servInfo из типа sockaddr_in в требуемый функции sockaddr* . Тогда итоговый код Этапа 3 (слава богу закончили) выглядит так:

Этап 4 (для сервера): «Прослушивание» привязанного порта для идентификации подключений

Серверная часть готова к прослушке подключающихся «Клиентов». Для того, чтобы реализовать данный этап, нужно вызвать функцию listen() , прототип которой:

int listen(SOCKET <«слушающий» сокет, который мы создавали на предыдущих этапах>, int <максимальное количество процессов, разрешенных к подключению>)

Второй аргумент: максимально возможное число подключений устанавливается через передачу параметр SOMAXCONN (рекомендуется). Если нужно установить ограничения на количество подключений – нужно указать SOMAXCONN_HINT(N) , где N – кол-во подключений. Если будет подключаться больше пользователей, то они будут сброшены.

После вызова данной функции исполнение программы приостанавливается до тех пор, пока не будет соединения с Клиентом, либо пока не будет возвращена ошибка прослушивания порта. Код Этапа 4 для Сервера:

Этап 4 (для Клиента). Организация подключения к серверу

Код для Клиента до текущего этапа выглядит даже проще: необходимо исполнение Этапов 0, 1 и 2. Привязка сокета к конкретному процессу ( bind() ) не требуется, т.к. сокет будет привязан к серверному Адресу и Порту через вызов функции connect() (по сути аналог bind() для Клиента). Собственно, после создания и инициализации сокета на клиентской стороне, нужно вызвать указанную функцию connect() . Её прототип:

int connect(SOCKET <инициализированный сокет>, sockaddr* <указатель на структуру, содержащую IP-адрес и Порт сервера>, int <размер структуры sockaddr>)

Функция возвращает 0 в случае успешного подключения и код ошибки в ином случае.

Процедура по добавлению данных в структуру sockaddr аналогична тому, как это делалось на Этапе 3 для Сервера при вызове функции bind() . Принципиально важный момент – в эту структуру для клиента должна заноситься информация о сервере, т.е. IPv4-адрес сервера и номер «слушающего» порта на сервере.

Этап 5 (только для Сервера). Подтверждение подключения

После начала прослушивания (вызов функции listen() ) следующей функцией должна идти функция accept() , которую будет искать программа после того, как установится соединение с Клиентом. Прототип функции accept() :

SOCKET accept(SOCKET <«слушающий» сокет на стороне Сервера>, sockaddr* <указатель на пустую структуру sockaddr, в которую будет записана информация по подключившемуся Клиенту>, int* <указатель на размер структуры типа sockaddr>)

Функция accept() возвращает номер дескриптора, под которым зарегистрирован сокет в ОС. Если произошла ошибка, то возвращается значение INVALID_SOCKET .

Если подключение подтверждено, то вся информация по текущему соединению передаётся на новый сокет, который будет отвечать со стороны Сервера за конкретное соединение с конкретным Клиентом. Перед вызовом accept() нам надо создать пустую структуру типа sockaddr_in , куда запишутся данные подключившегося Клиента после вызова accept() . Пример кода:

Всё, соединение между Клиентом и Сервером установлено! Самое время попробовать передать информацию от Клиента к Серверу и обратно. Как мы в начале и договорились, мы будет реализовывать простейший чат между ними.

Этап 6: Передача данных между Клиентом и Сервером

Принимать информацию на любой стороне можно с помощью функции recv() , которая при своём вызове блокирует исполнение кода программы до того момента, пока она не получит информацию от другой стороны, либо пока не произойдет ошибка в передаче или соединении.

Отправлять информацию с любой стороны можно с помощью функции send() . При вызове данной функции обычно никакого ожидания и блокировки не происходит, а переданные в неё данные сразу же отправляются другой стороне.

Рассмотрим прототипы функций recv() и send() :

int recv(SOCKET <сокет акцептованного соединения>, char[] <буфер для приёма информации с другой стороны>, int <размер буфера>, <флаги>)

int send(SOCKET <сокет акцептованного соединения>, char[] <буфер хранящий отсылаемую информацию>, int <размер буфера>, <флаги>)

Флаги в большинстве случаев игнорируются – передается значение 0.

Функции возвращают количество переданных/полученных по факту байт.

Как видно из прототипов, по своей структуре и параметрам эти функции совершенно одинаковые. Что важно знать:

и та, и другая функции не гарантируют целостности отправленной/полученной информации. Это значит, что при реализации прикладных задач по взаимодействию Клиента и Сервера с их использованием требуется принимать дополнительные меры для контроля того, что все посланные байты действительно посланы и, что еще более важно, получены в том же объеме на другой стороне

предельно внимательно надо относиться к параметру «размер буфера». Он должен в точности равняться реальному количеству передаваемых байт. Если он будет отличаться, то есть риск потери части информации или «замусориванию» отправляемой порции данных, что ведет к автоматической поломке данных в процессе отправки/приёма. И совсем замечательно будет, если размер буфера по итогу работы функции равен возвращаемому значению функции – размеру принятых/отправленных байт.

В качестве буфера рекомендую использовать не классические массивы в С-стиле, а стандартный класс С++ <vector> типа char, т.к. он показал себя как более надежный и гибкий механизм при передаче данных, в особенности при передаче текстовых строк, где важен терминальный символ и «чистота» передаваемого массива.

Сама по себе упаковка и отправка данных делается элементарным использованием функций чтения всей строки до нажатия кнопки Ввода — fgets() с последующим вызовом функции send() , а на другой стороне — приёмом информации через recv() и выводом буфера на экран через cout <<.

Процесс непрерывного перехода от send() к recv() и обратно реализуется через бесконечный цикл, из которого совершается выход по вводу особой комбинации клавиш. Пример блока кода для Серверной части:

Пришло время показать итоговый рабочий код для Сервера и Клиента. Чтобы не загромождать и так большой текст дополнительным кодом, даю ссылки на код на GitHub:

Несколько важных финальных замечаний:

В итоговом коде я не использую проверку на точное получение отосланной информации, т.к. при единичной (не циклической) отсылке небольшого пакета информации накладные расходы на проверку его получения и отправку ответа будут выше, чем выгоды от такой проверки. Иными словами – такие пакеты теряются редко, а проверять их целостность и факт доставки очень долго.

При тестировании примера также видно, что чат рабочий, но очень уж несовершенный. Наиболее проблемное место – невозможность отправить сообщение пока другая сторона не ответила на твоё предыдущее сообщение. Суть проблемы в том, что после отсылки сообщения сторона-отправитель вызывает функцию recv(), которая, как я писал выше, блокирует исполнение последующего кода, в том числе блокирует вызов прерываний для осуществления ввода. Это приводит к тому, что набирать сообщение и что-то отправлять невозможно до тех пор, пока процесс не получит ответ от другой стороны, и вызов функции recv() не будет завершен. Благо введенная информация с клавиатуры не будет потеряна, а, накапливаясь в системном буфере ввода/вывода, будет выведена на экран как только блокировка со стороны recv() будет снята. Таким образом, мы реализовали так называемый прямой полудуплексный канал связи. Сделать его полностью дуплексным в голой сокетной архитектуре достаточно нетривиальная задача, частично решаемая за счет создания нескольких параллельно работающих потоков или нитей (threads) исполнения. Один поток будет принимать информацию, а второй – отправлять.

В последующих статьях я покажу реализацию полноценного чата между двумя сторонами (поможет разобраться в понятии «нити процесса»), а также покажу полноценную реализацию прикладного протокола по копированию файлов с Сервера на Клиент.

Введение в сетевое программирование. Сокеты.¶

Сокет — это программный интерфейс для обеспечения информационного обмена между процессами.

Серверный — сокет, который принимает сообщения.

Клиентский — сокет, который отправляет сообщения.

Потоковые (на основе TCP, в коде обозначаются SOCK_STREAM ) — сокеты с установленным соединением на основе протокола TCP, передают поток байтов, который может быть двунаправленным — т.е. приложение может и получать и отправлять данные.

Дейтаграммные (на основе UDP, в коде обозначаются SOCK_DGRAM ) — сокеты, не требующие установления явного соединения между ними. Сообщение отправляется указанному сокету и, соответственно, может получаться от указанного сокета.

Сокет состоит из IP-адреса и порта.

IP-адрес — уникальный сетевой адрес узла в компьютерной сети, построенной по протоколу IP. В версии протокола IPv4 IP-адрес имеет длину 4 байта (например, 192.168.0.3), а в версии протокола IPv6 IP-адрес имеет длину 16 байт (например, 2001:0db8:85a3:0000:0000:8a2e:0370:7334). IP-адрес должен быть уникален.

Порт — натуральное число, записываемое в заголовках протоколов транспортного уровня (TCP, UDP и др.). Порт используется для определения процесса-получателя пакета в пределах одного хоста.

В python для работы с сокетами используется встроенная библиотека socket . Одной из основных функций модуля является функция socket() , которая возвращает объект типа сокет, обладающий соответствующими функциями для работы с соединением.:

socket.bind(address) — Привязывает сокет к адресу address (инициализирует IP-адрес и порт). Сокет не должен быть привязан до этого.

socket.listen([backlog]) — Переводит сервер в режим приема соединений. Параметр«backlog (int)« – количество соединений, которые будет принимать сервер.

socket.accept() — Принимает соединение и блокирует приложение в ожидании сообщения от клиента. В результате возвращает кортеж:

conn : объект соединения (сокет), который можно использовать для отправки/получения данных;

address : адрес клиента.

socket.recv(bufsize[, flags]) — Читает и возвращает данные в двоичном формате (набор байтов) из сокета. Параметр bufsize (int) – максимальное количество байтов в одном сообщении.

socket.send(bytes[, flags]) — Отправляет данные клиенту и возвращает количество отправленных байт. Параметр bytes (bytes) – двоичные данные.

socket.close() — Закрывает сокет.

Работа с сокетом во многом схожа с работой с файловым объектом. Принцип — открыли соединение — считали данные — закрыли соединение.

Создание серверного сокета: .. code

Создание клиентского сокета: .. code

Обратите внимание, клиент отправляет байтовую строку, а не обычную. Сервер так же принимает в качестве сообщения байтовую строку и должен в ответе вернуть объект того же типа.

Задания¶

Реализовать чат без графического интерфейса, который позволит обмениваться сообщениями только между клиентом и сервером. Клиент должен получать сообщения сервера в том числе.

С помощью модуля easygui (см. полезные ссылки), добавьте в разработанный чат простой графический интерфейс.

Разработайте приложение, которое будет запрашивать у пользователя название файла, а затем отправлять содержимое этого файла серверу. Сервер будет подсчитывать количество слов и возвращать ответ.

Добавьте к чату из задачи 2 чат-бота на стороне сервера. Добавьте 4-5 фраз, которые сервер будет отправлять по определённым условиям.

socket — Low-level networking interface¶

This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS, and probably additional platforms.

Some behavior may be platform dependent, since calls are made to the operating system socket APIs.

Availability : not Emscripten, not WASI.

This module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi . See WebAssembly platforms for more information.

The Python interface is a straightforward transliteration of the Unix system call and library interface for sockets to Python’s object-oriented style: the socket() function returns a socket object whose methods implement the various socket system calls. Parameter types are somewhat higher-level than in the C interface: as with read() and write() operations on Python files, buffer allocation on receive operations is automatic, and buffer length is implicit on send operations.

Classes that simplify writing network servers.

A TLS/SSL wrapper for socket objects.

Socket families¶

Depending on the system and the build options, various socket families are supported by this module.

The address format required by a particular socket object is automatically selected based on the address family specified when the socket object was created. Socket addresses are represented as follows:

The address of an AF_UNIX socket bound to a file system node is represented as a string, using the file system encoding and the ‘surrogateescape’ error handler (see PEP 383). An address in Linux’s abstract namespace is returned as a bytes-like object with an initial null byte; note that sockets in this namespace can communicate with normal file system sockets, so programs intended to run on Linux may need to deal with both types of address. A string or bytes-like object can be used for either type of address when passing it as an argument.

Changed in version 3.3: Previously, AF_UNIX socket paths were assumed to use UTF-8 encoding.

Changed in version 3.5: Writable bytes-like object is now accepted.

A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like ‘daring.cwi.nl’ or an IPv4 address like ‘100.50.200.5’ , and port is an integer.

For IPv4 addresses, two special forms are accepted instead of a host address: » represents INADDR_ANY , which is used to bind to all interfaces, and the string ‘<broadcast>’ represents INADDR_BROADCAST . This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.

For AF_INET6 address family, a four-tuple (host, port, flowinfo, scope_id) is used, where flowinfo and scope_id represent the sin6_flowinfo and sin6_scope_id members in struct sockaddr_in6 in C. For socket module methods, flowinfo and scope_id can be omitted just for backward compatibility. Note, however, omission of scope_id can cause problems in manipulating scoped IPv6 addresses.

Changed in version 3.7: For multicast addresses (with scope_id meaningful) address may not contain %scope_id (or zone id ) part. This information is superfluous and may be safely omitted (recommended).

AF_NETLINK sockets are represented as pairs (pid, groups) .

Linux-only support for TIPC is available using the AF_TIPC address family. TIPC is an open, non-IP based networked protocol designed for use in clustered computer environments. Addresses are represented by a tuple, and the fields depend on the address type. The general tuple form is (addr_type, v1, v2, v3 [, scope]) , where:

addr_type is one of TIPC_ADDR_NAMESEQ , TIPC_ADDR_NAME , or TIPC_ADDR_ID .

scope is one of TIPC_ZONE_SCOPE , TIPC_CLUSTER_SCOPE , and TIPC_NODE_SCOPE .

If addr_type is TIPC_ADDR_NAME , then v1 is the server type, v2 is the port identifier, and v3 should be 0.

If addr_type is TIPC_ADDR_NAMESEQ , then v1 is the server type, v2 is the lower port number, and v3 is the upper port number.

If addr_type is TIPC_ADDR_ID , then v1 is the node, v2 is the reference, and v3 should be set to 0.

A tuple (interface, ) is used for the AF_CAN address family, where interface is a string representing a network interface name like ‘can0’ . The network interface name » can be used to receive packets from all network interfaces of this family.

CAN_ISOTP protocol require a tuple (interface, rx_addr, tx_addr) where both additional parameters are unsigned long integer that represent a CAN identifier (standard or extended).

CAN_J1939 protocol require a tuple (interface, name, pgn, addr) where additional parameters are 64-bit unsigned integer representing the ECU name, a 32-bit unsigned integer representing the Parameter Group Number (PGN), and an 8-bit integer representing the address.

A string or a tuple (id, unit) is used for the SYSPROTO_CONTROL protocol of the PF_SYSTEM family. The string is the name of a kernel control using a dynamically assigned ID. The tuple can be used if ID and unit number of the kernel control are known or if a registered ID is used.

New in version 3.3.

AF_BLUETOOTH supports the following protocols and address formats:

BTPROTO_L2CAP accepts (bdaddr, psm) where bdaddr is the Bluetooth address as a string and psm is an integer.

BTPROTO_RFCOMM accepts (bdaddr, channel) where bdaddr is the Bluetooth address as a string and channel is an integer.

BTPROTO_HCI accepts (device_id,) where device_id is either an integer or a string with the Bluetooth address of the interface. (This depends on your OS; NetBSD and DragonFlyBSD expect a Bluetooth address while everything else expects an integer.)

Changed in version 3.2: NetBSD and DragonFlyBSD support added.

BTPROTO_SCO accepts bdaddr where bdaddr is a bytes object containing the Bluetooth address in a string format. (ex. b’12:23:34:45:56:67′ ) This protocol is not supported under FreeBSD.

AF_ALG is a Linux-only socket based interface to Kernel cryptography. An algorithm socket is configured with a tuple of two to four elements (type, name [, feat [, mask]]) , where:

type is the algorithm type as string, e.g. aead , hash , skcipher or rng .

name is the algorithm name and operation mode as string, e.g. sha256 , hmac(sha256) , cbc(aes) or drbg_nopr_ctr_aes256 .

feat and mask are unsigned 32bit integers.

Some algorithm types require more recent Kernels.

New in version 3.6.

AF_VSOCK allows communication between virtual machines and their hosts. The sockets are represented as a (CID, port) tuple where the context ID or CID and port are integers.

New in version 3.7.

AF_PACKET is a low-level interface directly to network devices. The packets are represented by the tuple (ifname, proto[, pkttype[, hatype[, addr]]]) where:

ifname — String specifying the device name.

proto — An in network-byte-order integer specifying the Ethernet protocol number.

pkttype — Optional integer specifying the packet type:

PACKET_HOST (the default) — Packet addressed to the local host.

PACKET_BROADCAST — Physical-layer broadcast packet.

PACKET_MULTICAST — Packet sent to a physical-layer multicast address.

PACKET_OTHERHOST — Packet to some other host that has been caught by a device driver in promiscuous mode.

PACKET_OUTGOING — Packet originating from the local host that is looped back to a packet socket.

hatype — Optional integer specifying the ARP hardware address type.

addr — Optional bytes-like object specifying the hardware physical address, whose interpretation depends on the device.

AF_QIPCRTR is a Linux-only socket based interface for communicating with services running on co-processors in Qualcomm platforms. The address family is represented as a (node, port) tuple where the node and port are non-negative integers.

New in version 3.8.

IPPROTO_UDPLITE is a variant of UDP which allows you to specify what portion of a packet is covered with the checksum. It adds two socket options that you can change. self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length) will change what portion of outgoing packets are covered by the checksum and self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length) will filter out packets which cover too little of their data. In both cases length should be in range(8, 2**16, 8) .

Such a socket should be constructed with socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE) for IPv4 or socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE) for IPv6.

New in version 3.9.

If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a nondeterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion.

All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised. Errors related to socket or address semantics raise OSError or one of its subclasses.

Non-blocking mode is supported through setblocking() . A generalization of this based on timeouts is supported through settimeout() .

Module contents¶

The module socket exports the following elements.

Exceptions¶

A deprecated alias of OSError .

Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError .

A subclass of OSError , this exception is raised for address-related errors, i.e. for functions that use h_errno in the POSIX C API, including gethostbyname_ex() and gethostbyaddr() . The accompanying value is a pair (h_errno, string) representing an error returned by a library call. h_errno is a numeric value, while string represents the description of h_errno, as returned by the hstrerror() C function.

Changed in version 3.3: This class was made a subclass of OSError .

A subclass of OSError , this exception is raised for address-related errors by getaddrinfo() and getnameinfo() . The accompanying value is a pair (error, string) representing an error returned by a library call. string represents the description of error, as returned by the gai_strerror() C function. The numeric error value will match one of the EAI_* constants defined in this module.

Changed in version 3.3: This class was made a subclass of OSError .

A deprecated alias of TimeoutError .

A subclass of OSError , this exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout() (or implicitly through setdefaulttimeout() ). The accompanying value is a string whose value is currently always “timed out”.

Changed in version 3.3: This class was made a subclass of OSError .

Changed in version 3.10: This class was made an alias of TimeoutError .

Constants¶

The AF_* and SOCK_* constants are now AddressFamily and SocketKind IntEnum collections.

New in version 3.4.

These constants represent the address (and protocol) families, used for the first argument to socket() . If the AF_UNIX constant is not defined then this protocol is unsupported. More constants may be available depending on the system.

socket. SOCK_STREAM ¶ socket. SOCK_DGRAM ¶ socket. SOCK_RAW ¶ socket. SOCK_RDM ¶ socket. SOCK_SEQPACKET ¶

These constants represent the socket types, used for the second argument to socket() . More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)

socket. SOCK_CLOEXEC ¶ socket. SOCK_NONBLOCK ¶

These two constants, if defined, can be combined with the socket types and allow you to set some flags atomically (thus avoiding possible race conditions and the need for separate calls).

New in version 3.2.

Many constants of these forms, documented in the Unix documentation on sockets and/or the IP protocol, are also defined in the socket module. They are generally used in arguments to the setsockopt() and getsockopt() methods of socket objects. In most cases, only those symbols that are defined in the Unix header files are defined; for a few symbols, default values are provided.

Changed in version 3.6: SO_DOMAIN , SO_PROTOCOL , SO_PEERSEC , SO_PASSSEC , TCP_USER_TIMEOUT , TCP_CONGESTION were added.

Changed in version 3.6.5: On Windows, TCP_FASTOPEN , TCP_KEEPCNT appear if run-time Windows supports.

Changed in version 3.7: TCP_NOTSENT_LOWAT was added.

On Windows, TCP_KEEPIDLE , TCP_KEEPINTVL appear if run-time Windows supports.

Changed in version 3.10: IP_RECVTOS was added. Added TCP_KEEPALIVE . On MacOS this constant can be used in the same way that TCP_KEEPIDLE is used on Linux.

Changed in version 3.11: Added TCP_CONNECTION_INFO . On MacOS this constant can be used in the same way that TCP_INFO is used on Linux and BSD.

Many constants of these forms, documented in the Linux documentation, are also defined in the socket module.

New in version 3.3.

Changed in version 3.11: NetBSD support was added.

CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol. Broadcast manager constants, documented in the Linux documentation, are also defined in the socket module.

The CAN_BCM_CAN_FD_FRAME flag is only available on Linux >= 4.8.

New in version 3.4.

Enables CAN FD support in a CAN_RAW socket. This is disabled by default. This allows your application to send both CAN and CAN FD frames; however, you must accept both CAN and CAN FD frames when reading from the socket.

This constant is documented in the Linux documentation.

New in version 3.5.

Joins the applied CAN filters such that only CAN frames that match all given CAN filters are passed to user space.

This constant is documented in the Linux documentation.

New in version 3.9.

CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol. ISO-TP constants, documented in the Linux documentation.

New in version 3.7.

CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol. J1939 constants, documented in the Linux documentation.

New in version 3.9.

Many constants of these forms, documented in the Linux documentation, are also defined in the socket module.

Many constants of these forms, documented in the Linux documentation, are also defined in the socket module.

New in version 3.3.

Constants for Windows’ WSAIoctl(). The constants are used as arguments to the ioctl() method of socket objects.

Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added.

TIPC related constants, matching the ones exported by the C socket API. See the TIPC documentation for more information.

socket. AF_ALG ¶ socket. SOL_ALG ¶ ALG_*

Constants for Linux Kernel cryptography.

New in version 3.6.

Constants for Linux host/guest communication.

New in version 3.7.

New in version 3.4.

This constant contains a boolean value which indicates if IPv6 is supported on this platform.

socket. BDADDR_ANY ¶ socket. BDADDR_LOCAL ¶

These are string constants containing Bluetooth addresses with special meanings. For example, BDADDR_ANY can be used to indicate any address when specifying the binding socket with BTPROTO_RFCOMM .

socket. HCI_FILTER ¶ socket. HCI_TIME_STAMP ¶ socket. HCI_DATA_DIR ¶

For use with BTPROTO_HCI . HCI_FILTER is not available for NetBSD or DragonFlyBSD. HCI_TIME_STAMP and HCI_DATA_DIR are not available for FreeBSD, NetBSD, or DragonFlyBSD.

Constant for Qualcomm’s IPC router protocol, used to communicate with service providing remote processors.

LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be used with SOCK_DGRAM, SOCK_STREAM sockets, equivalent to Linux/DragonFlyBSD SO_PASSCRED, while LOCAL_CREDS sends the credentials at first read, LOCAL_CREDS_PERSISTENT sends for each read, SCM_CREDS2 must be then used for the latter for the message type.

New in version 3.11.

Constant to optimize CPU locality, to be used in conjunction with SO_REUSEPORT .

New in version 3.11.

Functions¶

Creating sockets¶

The following functions all create socket objects .

class socket. socket ( family = AF_INET , type = SOCK_STREAM , proto = 0 , fileno = None ) ¶

Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 , AF_UNIX , AF_CAN , AF_PACKET , or AF_RDS . The socket type should be SOCK_STREAM (the default), SOCK_DGRAM , SOCK_RAW or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted or in the case where the address family is AF_CAN the protocol should be one of CAN_RAW , CAN_BCM , CAN_ISOTP or CAN_J1939 .

If fileno is specified, the values for family, type, and proto are auto-detected from the specified file descriptor. Auto-detection can be overruled by calling the function with explicit family, type, or proto arguments. This only affects how Python represents e.g. the return value of socket.getpeername() but not the actual OS resource. Unlike socket.fromfd() , fileno will return the same socket and not a duplicate. This may help close a detached socket using socket.close() .

The newly created socket is non-inheritable .

Raises an auditing event socket.__new__ with arguments self , family , type , protocol .

Changed in version 3.3: The AF_CAN family was added. The AF_RDS family was added.

Changed in version 3.4: The CAN_BCM protocol was added.

Changed in version 3.4: The returned socket is now non-inheritable.

Changed in version 3.7: The CAN_ISOTP protocol was added.

Changed in version 3.7: When SOCK_NONBLOCK or SOCK_CLOEXEC bit flags are applied to type they are cleared, and socket.type will not reflect them. They are still passed to the underlying system socket() call. Therefore,

will still create a non-blocking socket on OSes that support SOCK_NONBLOCK , but sock.type will be set to socket.SOCK_STREAM .

Changed in version 3.9: The CAN_J1939 protocol was added.

Changed in version 3.10: The IPPROTO_MPTCP protocol was added.

Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the socket() function above. The default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET .

The newly created sockets are non-inheritable .

Changed in version 3.2: The returned socket objects now support the whole socket API, rather than a subset.

Changed in version 3.4: The returned sockets are now non-inheritable.

Changed in version 3.5: Windows support added.

Connect to a TCP service listening on the internet address (a 2-tuple (host, port) ), and return the socket object. This is a higher-level function than socket.connect() : if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6 , and then try to connect to all possible addresses in turn until a connection succeeds. This makes it easy to write clients that are compatible to both IPv4 and IPv6.

Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned by getdefaulttimeout() is used.

If supplied, source_address must be a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.

When a connection cannot be created, an exception is raised. By default, it is the exception from the last address in the list. If all_errors is True , it is an ExceptionGroup containing the errors of all attempts.

Changed in version 3.2: source_address was added.

Changed in version 3.11: all_errors was added.

Convenience function which creates a TCP socket bound to address (a 2-tuple (host, port) ) and return the socket object.

family should be either AF_INET or AF_INET6 . backlog is the queue size passed to socket.listen() ; if not specified , a default reasonable value is chosen. reuse_port dictates whether to set the SO_REUSEPORT socket option.

If dualstack_ipv6 is true and the platform supports it the socket will be able to accept both IPv4 and IPv6 connections, else it will raise ValueError . Most POSIX platforms and Windows are supposed to support this functionality. When this functionality is enabled the address returned by socket.getpeername() when an IPv4 connection occurs will be an IPv6 address represented as an IPv4-mapped IPv6 address. If dualstack_ipv6 is false it will explicitly disable this functionality on platforms that enable it by default (e.g. Linux). This parameter can be used in conjunction with has_dualstack_ipv6() :

On POSIX platforms the SO_REUSEADDR socket option is set in order to immediately reuse previous sockets which were bound on the same address and remained in TIME_WAIT state.

New in version 3.8.

Return True if the platform supports creating a TCP socket which can handle both IPv4 and IPv6 connections.

New in version 3.8.

Duplicate the file descriptor fd (an integer as returned by a file object’s fileno() method) and build a socket object from the result. Address family, socket type and protocol number are as for the socket() function above. The file descriptor should refer to a socket, but this is not checked — subsequent operations on the object may fail if the file descriptor is invalid. This function is rarely needed, but can be used to get or set socket options on a socket passed to a program as standard input or output (such as a server started by the Unix inet daemon). The socket is assumed to be in blocking mode.

The newly created socket is non-inheritable .

Changed in version 3.4: The returned socket is now non-inheritable.

Instantiate a socket from data obtained from the socket.share() method. The socket is assumed to be in blocking mode.

New in version 3.3.

This is a Python type object that represents the socket object type. It is the same as type(socket(. )) .

Other functions¶

The socket module also offers various network-related services:

Close a socket file descriptor. This is like os.close() , but for sockets. On some platforms (most noticeable Windows) os.close() does not work for socket file descriptors.

New in version 3.7.

Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or None . port is a string service name such as ‘http’ , a numeric port number or None . By passing None as the value of host and port, you can pass NULL to the underlying C API.

The family, type and proto arguments can be optionally specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results. The flags argument can be one or several of the AI_* constants, and will influence how results are computed and returned. For example, AI_NUMERICHOST will disable domain name resolution and will raise an error if host is a domain name.

The function returns a list of 5-tuples with the following structure:

(family, type, proto, canonname, sockaddr)

In these tuples, family, type, proto are all integers and are meant to be passed to the socket() function. canonname will be a string representing the canonical name of the host if AI_CANONNAME is part of the flags argument; else canonname will be empty. sockaddr is a tuple describing a socket address, whose format depends on the returned family (a (address, port) 2-tuple for AF_INET , a (address, port, flowinfo, scope_id) 4-tuple for AF_INET6 ), and is meant to be passed to the socket.connect() method.

Raises an auditing event socket.getaddrinfo with arguments host , port , family , type , protocol .

The following example fetches address information for a hypothetical TCP connection to example.org on port 80 (results may differ on your system if IPv6 isn’t enabled):

Changed in version 3.2: parameters can now be passed using keyword arguments.

Changed in version 3.7: for IPv6 multicast addresses, string representing an address will not contain %scope_id part.

Return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host. To find the fully qualified name, the hostname returned by gethostbyaddr() is checked, followed by aliases for the host, if available. The first name which includes a period is selected. In case no fully qualified domain name is available and name was provided, it is returned unchanged. If name was empty or equal to ‘0.0.0.0’ , the hostname from gethostname() is returned.

socket. gethostbyname ( hostname ) ¶

Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as ‘100.50.200.5’ . If the host name is an IPv4 address itself it is returned unchanged. See gethostbyname_ex() for a more complete interface. gethostbyname() does not support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.

Raises an auditing event socket.gethostbyname with argument hostname .

Translate a host name to IPv4 address format, extended interface. Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the host’s primary host name, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4 addresses for the same interface on the same host (often but not always a single address). gethostbyname_ex() does not support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.

Raises an auditing event socket.gethostbyname with argument hostname .

Return a string containing the hostname of the machine where the Python interpreter is currently executing.

Raises an auditing event socket.gethostname with no arguments.

Note: gethostname() doesn’t always return the fully qualified domain name; use getfqdn() for that.

Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4/v6 addresses for the same interface on the same host (most likely containing only a single address). To find the fully qualified domain name, use the function getfqdn() . gethostbyaddr() supports both IPv4 and IPv6.

Raises an auditing event socket.gethostbyaddr with argument ip_address .

Translate a socket address sockaddr into a 2-tuple (host, port) . Depending on the settings of flags, the result can contain a fully qualified domain name or numeric address representation in host. Similarly, port can contain a string port name or a numeric port number.

Читать:
Seagate discwizard как пользоваться

For IPv6 addresses, %scope_id is appended to the host part if sockaddr contains meaningful scope_id. Usually this happens for multicast addresses.

For more information about flags you can consult getnameinfo(3).

Raises an auditing event socket.getnameinfo with argument sockaddr .

Translate an internet protocol name (for example, ‘icmp’ ) to a constant suitable for passing as the (optional) third argument to the socket() function. This is usually only needed for sockets opened in “raw” mode ( SOCK_RAW ); for the normal socket modes, the correct protocol is chosen automatically if the protocol is omitted or zero.

Translate an internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be ‘tcp’ or ‘udp’ , otherwise any protocol will match.

Raises an auditing event socket.getservbyname with arguments servicename , protocolname .

Translate an internet port number and protocol name to a service name for that service. The optional protocol name, if given, should be ‘tcp’ or ‘udp’ , otherwise any protocol will match.

Raises an auditing event socket.getservbyport with arguments port , protocolname .

Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

Changed in version 3.10: Raises OverflowError if x does not fit in a 16-bit unsigned integer.

Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

Changed in version 3.10: Raises OverflowError if x does not fit in a 16-bit unsigned integer.

Convert an IPv4 address from dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format, as a bytes object four characters in length. This is useful when conversing with a program that uses the standard C library and needs objects of type in_addr , which is the C type for the 32-bit packed binary this function returns.

inet_aton() also accepts strings with less than three dots; see the Unix manual page inet(3) for details.

If the IPv4 address string passed to this function is invalid, OSError will be raised. Note that exactly what is valid depends on the underlying C implementation of inet_aton() .

inet_aton() does not support IPv6, and inet_pton() should be used instead for IPv4/v6 dual stack support.

socket. inet_ntoa ( packed_ip ) ¶

Convert a 32-bit packed IPv4 address (a bytes-like object four bytes in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type in_addr , which is the C type for the 32-bit packed binary data this function takes as an argument.

If the byte sequence passed to this function is not exactly 4 bytes in length, OSError will be raised. inet_ntoa() does not support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual stack support.

Changed in version 3.5: Writable bytes-like object is now accepted.

Convert an IP address from its family-specific string format to a packed, binary format. inet_pton() is useful when a library or network protocol calls for an object of type in_addr (similar to inet_aton() ) or in6_addr .

Supported values for address_family are currently AF_INET and AF_INET6 . If the IP address string ip_string is invalid, OSError will be raised. Note that exactly what is valid depends on both the value of address_family and the underlying implementation of inet_pton() .

Changed in version 3.4: Windows support added

Convert a packed IP address (a bytes-like object of some number of bytes) to its standard, family-specific string representation (for example, ‘7.10.0.5’ or ‘5aef:2b::8’ ). inet_ntop() is useful when a library or network protocol returns an object of type in_addr (similar to inet_ntoa() ) or in6_addr .

Supported values for address_family are currently AF_INET and AF_INET6 . If the bytes object packed_ip is not the correct length for the specified address family, ValueError will be raised. OSError is raised for errors from the call to inet_ntop() .

Changed in version 3.4: Windows support added

Changed in version 3.5: Writable bytes-like object is now accepted.

Return the total length, without trailing padding, of an ancillary data item with associated data of the given length. This value can often be used as the buffer size for recvmsg() to receive a single item of ancillary data, but RFC 3542 requires portable applications to use CMSG_SPACE() and thus include space for padding, even when the item will be the last in the buffer. Raises OverflowError if length is outside the permissible range of values.

Availability : Unix, not Emscripten, not WASI.

Most Unix platforms.

New in version 3.3.

Return the buffer size needed for recvmsg() to receive an ancillary data item with associated data of the given length, along with any trailing padding. The buffer space needed to receive multiple items is the sum of the CMSG_SPACE() values for their associated data lengths. Raises OverflowError if length is outside the permissible range of values.

Note that some systems might support ancillary data without providing this function. Also note that setting the buffer size using the results of this function may not precisely limit the amount of ancillary data that can be received, since additional data may be able to fit into the padding area.

Availability : Unix, not Emscripten, not WASI.

most Unix platforms.

New in version 3.3.

Return the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None .

socket. setdefaulttimeout ( timeout ) ¶

Set the default timeout in seconds (float) for new socket objects. When the socket module is first imported, the default is None . See settimeout() for possible values and their respective meanings.

socket. sethostname ( name ) ¶

Set the machine’s hostname to name. This will raise an OSError if you don’t have enough rights.

Raises an auditing event socket.sethostname with argument name .

New in version 3.3.

Return a list of network interface information (index int, name string) tuples. OSError if the system call fails.

Availability : Unix, Windows, not Emscripten, not WASI.

New in version 3.3.

Changed in version 3.8: Windows support was added.

On Windows network interfaces have different names in different contexts (all names are examples):

friendly name: vEthernet (nat)

description: Hyper-V Virtual Ethernet Adapter

This function returns names of the second form from the list, ethernet_32770 in this example case.

Return a network interface index number corresponding to an interface name. OSError if no interface with the given name exists.

Availability : Unix, Windows, not Emscripten, not WASI.

New in version 3.3.

Changed in version 3.8: Windows support was added.

“Interface name” is a name as documented in if_nameindex() .

Return a network interface name corresponding to an interface index number. OSError if no interface with the given index exists.

Availability : Unix, Windows, not Emscripten, not WASI.

New in version 3.3.

Changed in version 3.8: Windows support was added.

“Interface name” is a name as documented in if_nameindex() .

Send the list of file descriptors fds over an AF_UNIX socket sock. The fds parameter is a sequence of file descriptors. Consult sendmsg() for the documentation of these parameters.

Availability : Unix, Windows, not Emscripten, not WASI.

Unix platforms supporting sendmsg() and SCM_RIGHTS mechanism.

New in version 3.9.

Receive up to maxfds file descriptors from an AF_UNIX socket sock. Return (msg, list(fds), flags, addr) . Consult recvmsg() for the documentation of these parameters.

Availability : Unix, Windows, not Emscripten, not WASI.

Unix platforms supporting sendmsg() and SCM_RIGHTS mechanism.

New in version 3.9.

Any truncated integers at the end of the list of file descriptors.

Socket Objects¶

Socket objects have the following methods. Except for makefile() , these correspond to Unix system calls applicable to sockets.

Changed in version 3.2: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling close() .

Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

The newly created socket is non-inheritable .

Changed in version 3.4: The socket is now non-inheritable.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — see above.)

Raises an auditing event socket.bind with arguments self , address .

Mark the socket closed. The underlying system resource (e.g. a file descriptor) is also closed when all file objects from makefile() are closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed).

Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them.

Changed in version 3.6: OSError is now raised if an error occurs when the underlying close() call is made.

close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close() .

Connect to a remote socket at address. (The format of address depends on the address family — see above.)

If the connection is interrupted by a signal, the method waits until the connection completes, or raise a TimeoutError on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler).

Raises an auditing event socket.connect with arguments self , address .

Changed in version 3.5: The method now waits until the connection completes instead of raising an InterruptedError exception if the connection is interrupted by a signal, the signal handler doesn’t raise an exception and the socket is blocking or has a timeout (see the PEP 475 for the rationale).

Like connect(address) , but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.

Raises an auditing event socket.connect with arguments self , address .

Put the socket object into closed state without actually closing the underlying file descriptor. The file descriptor is returned, and can be reused for other purposes.

New in version 3.2.

Duplicate the socket.

The newly created socket is non-inheritable .

Changed in version 3.4: The socket is now non-inheritable.

Return the socket’s file descriptor (a small integer), or -1 on failure. This is useful with select.select() .

Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen() ). Unix does not have this limitation.

Get the inheritable flag of the socket’s file descriptor or socket’s handle: True if the socket can be inherited in child processes, False if it cannot.

New in version 3.4.

Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.

Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.)

socket. getsockopt ( level , optname [ , buflen ] ) ¶

Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants ( SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a bytes object. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as byte strings).

Return True if socket is in blocking mode, False if in non-blocking.

This is equivalent to checking socket.gettimeout() == 0 .

New in version 3.7.

Return the timeout in seconds (float) associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() or settimeout() .

socket. ioctl ( control , option ) ¶ Platform

The ioctl() method is a limited interface to the WSAIoctl system interface. Please refer to the Win32 documentation for more information.

On other platforms, the generic fcntl.fcntl() and fcntl.ioctl() functions may be used; they accept a socket object as their first argument.

Currently only the following control codes are supported: SIO_RCVALL , SIO_KEEPALIVE_VALS , and SIO_LOOPBACK_FAST_PATH .

Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added.

Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.

Changed in version 3.5: The backlog parameter is now optional.

Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile() . These arguments are interpreted the same way as by the built-in open() function, except the only supported mode values are ‘r’ (default), ‘w’ and ‘b’ .

The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in an inconsistent state if a timeout occurs.

Closing the file object returned by makefile() won’t close the original socket unless all other file objects have been closed and socket.close() has been called on the socket object.

On Windows, the file-like object created by makefile() cannot be used where a file object with a file descriptor is expected, such as the stream arguments of subprocess.Popen() .

Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Changed in version 3.7: For multicast IPv6 address, first item of address does not contain %scope_id part anymore. In order to get full IPv6 address use getnameinfo() .

Receive normal data (up to bufsize bytes) and ancillary data from the socket. The ancbufsize argument sets the size in bytes of the internal buffer used to receive the ancillary data; it defaults to 0, meaning that no ancillary data will be received. Appropriate buffer sizes for ancillary data can be calculated using CMSG_SPACE() or CMSG_LEN() , and items which do not fit into the buffer might be truncated or discarded. The flags argument defaults to 0 and has the same meaning as for recv() .

The return value is a 4-tuple: (data, ancdata, msg_flags, address) . The data item is a bytes object holding the non-ancillary data received. The ancdata item is a list of zero or more tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data (control messages) received: cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes object holding the associated data. The msg_flags item is the bitwise OR of various flags indicating conditions on the received message; see your system documentation for details. If the receiving socket is unconnected, address is the address of the sending socket, if available; otherwise, its value is unspecified.

On some systems, sendmsg() and recvmsg() can be used to pass file descriptors between processes over an AF_UNIX socket. When this facility is used (it is often restricted to SOCK_STREAM sockets), recvmsg() will return, in its ancillary data, items of the form (socket.SOL_SOCKET, socket.SCM_RIGHTS, fds) , where fds is a bytes object representing the new file descriptors as a binary array of the native C int type. If recvmsg() raises an exception after the system call returns, it will first attempt to close any file descriptors received via this mechanism.

Some systems do not indicate the truncated length of ancillary data items which have been only partially received. If an item appears to extend beyond the end of the buffer, recvmsg() will issue a RuntimeWarning , and will return the part of it which is inside the buffer provided it has not been truncated before the start of its associated data.

On systems which support the SCM_RIGHTS mechanism, the following function will receive up to maxfds file descriptors, returning the message data and a list containing the descriptors (while ignoring unexpected conditions such as unrelated control messages being received). See also sendmsg() .

Most Unix platforms.

New in version 3.3.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Receive normal data and ancillary data from the socket, behaving as recvmsg() would, but scatter the non-ancillary data into a series of buffers instead of returning a new bytes object. The buffers argument must be an iterable of objects that export writable buffers (e.g. bytearray objects); these will be filled with successive chunks of the non-ancillary data until it has all been written or there are no more buffers. The operating system may set a limit ( sysconf() value SC_IOV_MAX ) on the number of buffers that can be used. The ancbufsize and flags arguments have the same meaning as for recvmsg() .

The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address) , where nbytes is the total number of bytes of non-ancillary data written into the buffers, and ancdata, msg_flags and address are the same as for recvmsg() .

Most Unix platforms.

New in version 3.3.

Receive data from the socket, writing it into buffer instead of creating a new bytestring. The return value is a pair (nbytes, address) where nbytes is the number of bytes received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

socket. recv_into ( buffer [ , nbytes [ , flags ] ] ) ¶

Receive up to nbytes bytes from the socket, storing the data into a buffer rather than creating a new bytestring. If nbytes is not specified (or 0), receive up to the size available in the given buffer. Returns the number of bytes received. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

socket. send ( bytes [ , flags ] ) ¶

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO .

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send() , this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.

Changed in version 3.5: The socket timeout is no more reset each time data is sent successfully. The socket timeout is now the maximum total duration to send all data.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

Raises an auditing event socket.sendto with arguments self , address .

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Send normal and ancillary data to the socket, gathering the non-ancillary data from a series of buffers and concatenating it into a single message. The buffers argument specifies the non-ancillary data as an iterable of bytes-like objects (e.g. bytes objects); the operating system may set a limit ( sysconf() value SC_IOV_MAX ) on the number of buffers that can be used. The ancdata argument specifies the ancillary data (control messages) as an iterable of zero or more tuples (cmsg_level, cmsg_type, cmsg_data) , where cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes-like object holding the associated data. Note that some systems (in particular, systems without CMSG_SPACE() ) might support sending only one control message per call. The flags argument defaults to 0 and has the same meaning as for send() . If address is supplied and not None , it sets a destination address for the message. The return value is the number of bytes of non-ancillary data sent.

The following function sends the list of file descriptors fds over an AF_UNIX socket, on systems which support the SCM_RIGHTS mechanism. See also recvmsg() .

Most Unix platforms.

Raises an auditing event socket.sendmsg with arguments self , address .

New in version 3.3.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

Specialized version of sendmsg() for AF_ALG socket. Set mode, IV, AEAD associated data length and flags for AF_ALG socket.

New in version 3.6.

Send a file until EOF is reached by using high-performance os.sendfile and return the total number of bytes which were sent. file must be a regular file object opened in binary mode. If os.sendfile is not available (e.g. Windows) or file is not a regular file send() will be used instead. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. The socket must be of SOCK_STREAM type. Non-blocking sockets are not supported.

New in version 3.5.

Set the inheritable flag of the socket’s file descriptor or socket’s handle.

New in version 3.4.

Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode.

This method is a shorthand for certain settimeout() calls:

sock.setblocking(True) is equivalent to sock.settimeout(None)

sock.setblocking(False) is equivalent to sock.settimeout(0.0)

Changed in version 3.7: The method no longer applies SOCK_NONBLOCK flag on socket.type .

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None . If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

For further information, please consult the notes on socket timeouts .

Changed in version 3.7: The method no longer toggles SOCK_NONBLOCK flag on socket.type .

Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module ( SO_* etc.). The value can be an integer, None or a bytes-like object representing a buffer. In the later case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in module struct for a way to encode C structures as bytestrings). When value is set to None , optlen argument is required. It’s equivalent to call setsockopt() C function with optval=NULL and optlen=optlen .

Changed in version 3.5: Writable bytes-like object is now accepted.

Changed in version 3.6: setsockopt(level, optname, None, optlen: int) form added.

Shut down one or both halves of the connection. If how is SHUT_RD , further receives are disallowed. If how is SHUT_WR , further sends are disallowed. If how is SHUT_RDWR , further sends and receives are disallowed.

Duplicate a socket and prepare it for sharing with a target process. The target process must be provided with process_id. The resulting bytes object can then be passed to the target process using some form of interprocess communication and the socket can be recreated there using fromshare() . Once this method has been called, it is safe to close the socket since the operating system has already duplicated it for the target process.

New in version 3.3.

Note that there are no methods read() or write() ; use recv() and send() without flags argument instead.

Socket objects also have these (read-only) attributes that correspond to the values given to the socket constructor.

The socket family.

The socket type.

The socket protocol.

Notes on socket timeouts¶

A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are by default always created in blocking mode, but this can be changed by calling setdefaulttimeout() .

In blocking mode, operations block until complete or the system returns an error (such as connection timed out).

In non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately: functions from the select can be used to know when and whether a socket is available for reading or writing.

In timeout mode, operations fail if they cannot be completed within the timeout specified for the socket (they raise a timeout exception) or if the system returns an error.

At the operating system level, sockets in timeout mode are internally set in non-blocking mode. Also, the blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. This implementation detail can have visible consequences if e.g. you decide to use the fileno() of a socket.

Timeouts and the connect method¶

The connect() operation is also subject to the timeout setting, and in general it is recommended to call settimeout() before calling connect() or pass a timeout parameter to create_connection() . However, the system network stack may also return a connection timeout error of its own regardless of any Python socket timeout setting.

Timeouts and the accept method¶

If getdefaulttimeout() is not None , sockets returned by the accept() method inherit that timeout. Otherwise, the behaviour depends on settings of the listening socket:

if the listening socket is in blocking mode or in timeout mode, the socket returned by accept() is in blocking mode;

if the listening socket is in non-blocking mode, whether the socket returned by accept() is in blocking or non-blocking mode is operating system-dependent. If you want to ensure cross-platform behaviour, it is recommended you manually override this setting.

Example¶

Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence socket() , bind() , listen() , accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket() , connect() . Also note that the server does not sendall() / recv() on the socket it is listening on but on the new socket returned by accept() .

The first two examples support IPv4 only.

The next two examples are identical to the above two, but support both IPv4 and IPv6. The server side will listen to the first address family available (it should listen to both instead). On most of IPv6-ready systems, IPv6 will take precedence and the server may not accept IPv4 traffic. The client side will try to connect to the all addresses returned as a result of the name resolution, and sends traffic to the first one connected successfully.

The next example shows how to write a very simple network sniffer with raw sockets on Windows. The example requires administrator privileges to modify the interface:

The next example shows how to use the socket interface to communicate to a CAN network using the raw socket protocol. To use CAN with the broadcast manager protocol instead, open a socket with:

After binding ( CAN_RAW ) or connecting ( CAN_BCM ) the socket, you can use the socket.send() , and the socket.recv() operations (and their counterparts) on the socket object as usual.

This last example might require special privileges:

Running an example several times with too small delay between executions, could lead to this error:

This is because the previous execution has left the socket in a TIME_WAIT state, and can’t be immediately reused.

There is a socket flag to set, in order to prevent this, socket.SO_REUSEADDR :

the SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

For an introduction to socket programming (in C), see the following papers:

An Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest

An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J. Leffler et al,

both in the UNIX Programmer’s Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The platform-specific reference material for the various socket-related system calls are also a valuable source of information on the details of socket semantics. For Unix, refer to the manual pages; for Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may want to refer to RFC 3493 titled Basic Socket Interface Extensions for IPv6.

Сокеты в C

#include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h>

Хочу обратить Ваше внимание на то, что библиотеки sys/types, sys/socket не подключатся если Вы работаете в Windows с компилятором MinGW.

Попробуйте компилировать с помощью подсистемы Linux для Windows .

Создание сокета

Сокет в Си создаётся следующим образом:

int socket( int domain, int type, int protocol);

domain: Аргументом является семейство протоколов. Если Вы планируете использовать IPv4 укажите домен AF_INET.

Если нужен IPv6 то AF_INET6. Полный список смотрите в разделе MAN DESCRIPTION

type: Обычно выбирают SOCK_STREAM это надёжная упорядоченная передача байтов в режиме полный дуплекс.

protocol: Обычно выбирают 0. Если Вам нужен не 0, то Вы уже, видимо, знаете, что делаете лучше меня.

Типичный вариант создания сокета выглядит так:

int socket(AF_INET, SOCK_STREAM, 0);

TCP Сервер

TCP Сервер v 2

Более продвинутая версия

TCP Клиент

Socket Man

Чтобы прочитать справочную информацию о socket введите

Если man не установлен прочитайте инструкцию по установке здесь

SOCKET(2) Linux Programmer's Manual SOCKET(2) NAME socket — create an endpoint for communication SYNOPSIS #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int socket( int domain, int type, int protocol);

DESCRIPTION socket() creates an endpoint for communication and returns a file descriptor that refers to that endpoint. The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process. The domain argument specifies a communication domain; this selects the protocol family which will be used for communication. These families are defined in <sys/socket.h>. The currently understood formats include: Name Purpose Man page AF_UNIX, AF_LOCAL Local communication unix(7) AF_INET IPv4 Internet protocols ip(7) AF_INET6 IPv6 Internet protocols ipv6(7) AF_IPX IPX — Novell protocols AF_NETLINK Kernel user interface device netlink(7) AF_X25 ITU-T X.25 / ISO-8208 protocol x25(7) AF_AX25 Amateur radio AX.25 protocol AF_ATMPVC Access to raw ATM PVCs AF_APPLETALK AppleTalk ddp(7) AF_PACKET Low level packet interface packet(7) AF_ALG Interface to kernel crypto API The socket has the indicated type, which specifies the communication semantics.

Currently defined types are: SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported. SOCK_DGRAM Supports datagrams (connectionless, unreliable messages of a fixed maximum length). SOCK_SEQPACKET Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each input system call. SOCK_RAW Provides raw network protocol access. SOCK_RDM Provides a reliable datagram layer that does not guarantee ordering. SOCK_PACKET Obsolete and should not be used in new programs; see packet(7). Some socket types may not be implemented by all protocol families. Since Linux 2.6.27, the type argument serves a second purpose: in addition to specifying a socket type, it may include the bitwise OR of any of the following values, to modify the behavior of socket(): SOCK_NONBLOCK Set the O_NONBLOCK file status flag on the new open file description. Using this flag saves extra calls to fcntl(2) to achieve the same result. SOCK_CLOEXEC Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the description of the O_CLOEXEC flag in open(2) for reasons why this may be useful. The protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family, in which case protocol can be specified as 0. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. The protocol number to use is specific to the “communication domain” in which communication is to take place; see protocols(5). See getprotoent(3) on how to map protocol name strings to protocol numbers. Sockets of type SOCK_STREAM are full-duplex byte streams. They do not preserve record boundaries. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect(2) call. Once connected, data may be transferred using read(2) and write(2) calls or some variant of the send(2) and recv(2) calls. When a session has been completed a close(2) may be performed. Out-of-band data may also be transmitted as described in send(2) and received as described in recv(2). The communications protocols which implement a SOCK_STREAM ensure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered to be dead. When SO_KEEPALIVE is enabled on the socket the protocol checks in a protocol-specific manner if the other end is still alive. A SIGPIPE signal is raised if a process sends or receives on a broken stream; this causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET sockets employ the same system calls as SOCK_STREAM sockets. The only difference is that read(2) calls will return only the amount of data requested, and any data remaining in the arriving packet will be discarded. Also all message boundaries in incoming datagrams are preserved. SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams to correspondents named in sendto(2) calls. Datagrams are generally received with recvfrom(2), which returns the next datagram along with the address of its sender. SOCK_PACKET is an obsolete socket type to receive raw packets directly from the device driver. Use packet(7) instead. An fcntl(2) F_SETOWN operation can be used to specify a process or process group to receive a SIGURG signal when the out-of-band data arrives or SIGPIPE signal when a SOCK_STREAM connection breaks unexpectedly. This operation may also be used to set the process or process group that receives the I/O and asynchronous notification of I/O events via SIGIO. Using F_SETOWN is equivalent to an ioctl(2) call with the FIOSETOWN or SIOCSPGRP argument. When the network signals an error condition to the protocol module (e.g., using an ICMP message for IP) the pending error flag is set for the socket. The next operation on this socket will return the error code of the pending error. For some protocols it is possible to enable a per-socket error queue to retrieve detailed information about the error; see IP_RECVERR in ip(7). The operation of sockets is controlled by socket level options. These options are defined in <sys/socket.h>. The functions setsockopt(2) and getsockopt(2) are used to set and get options, respectively. RETURN VALUE On success, a file descriptor for the new socket is returned. On error, -1 is returned, and errno is set appropriately. ERRORS EACCES Permission to create a socket of the specified type and/or protocol is denied. EAFNOSUPPORT The implementation does not support the specified address family. EINVAL Unknown protocol, or protocol family not available. EINVAL Invalid flags in type. EMFILE The per-process limit on the number of open file descriptors has been reached. ENFILE The system-wide limit on the total number of open files has been reached. ENOBUFS or ENOMEM Insufficient memory is available. The socket cannot be created until sufficient resources are freed. EPROTONOSUPPORT The protocol type or the specified protocol is not supported within this domain. Other errors may be generated by the underlying protocol modules. CONFORMING TO POSIX.1-2001, POSIX.1-2008, 4.4BSD. The SOCK_NONBLOCK and SOCK_CLOEXEC flags are Linux-specific. socket() appeared in 4.2BSD. It is generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants). NOTES POSIX.1 does not require the inclusion of <sys/types.h>, and this header file is not required on Linux. However, some historical (BSD) implementations required this header file, and portable applications are probably wise to include it. The manifest constants used under 4.x BSD for protocol families are PF_UNIX, PF_INET, and so on, while AF_UNIX, AF_INET, and so on are used for address families. However, already the BSD man page promises: «The protocol family generally is the same as the address family», and subsequent standards use AF_* everywhere. The AF_ALG protocol type was added in Linux 2.6.38. More information on this interface is provided with the kernel HTML documentation at https://www.kernel.org/doc/htmldocs/crypto-API/User.html. EXAMPLE An example of the use of socket() is shown in getaddrinfo(3). SEE ALSO accept(2), bind(2), close(2), connect(2), fcntl(2), getpeername(2), getsockname(2), getsockopt(2), ioctl(2), listen(2), read(2), recv(2), select(2), send(2), shutdown(2), socketpair(2), write(2), getprotoent(3), ip(7), socket(7), tcp(7), udp(7), unix(7) “An Introductory 4.3BSD Interprocess Communication Tutorial” and “BSD Interprocess Communication Tutorial”, reprinted in UNIX Programmer's Supplementary Documents Volume 1. COLOPHON This page is part of release 4.16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/. Linux 2017-09-15 SOCKET(2)

sys/socket.h

The Single UNIX ® Specification, Version 2 Copyright © 1997 The Open Group NAME sys/socket.h — Internet Protocol family SYNOPSIS #include <sys/socket.h> DESCRIPTION <sys/socket.h> makes available a type, socklen_t, which is an unsigned opaque integral type of length of at least 32 bits. To forestall portability problems, it is recommended that applications should not use values larger than 232 — 1. The <sys/socket.h> header defines the unsigned integral type sa_family_t. The <sys/socket.h> header defines the sockaddr structure that includes at least the following members: sa_family_t sa_family address family char sa_data[] socket address (variable-length data) The <sys/socket.h> header defines the msghdr structure that includes at least the following members: void *msg_name optional address socklen_t msg_namelen size of address struct iovec *msg_iov scatter/gather array int msg_iovlen members in msg_iov void *msg_control ancillary data, see below socklen_t msg_controllen ancillary data buffer len int msg_flags flags on received message The <sys/socket.h> header defines the cmsghdr structure that includes at least the following members: socklen_t cmsg_len data byte count, including the cmsghdr int cmsg_level originating protocol int cmsg_type protocol-specific type Ancillary data consists of a sequence of pairs, each consisting of a cmsghdr structure followed by a data array. The data array contains the ancillary data message, and the cmsghdr structure contains descriptive information that allows an application to correctly parse the data. The values for cmsg_level will be legal values for the level argument to the getsockopt() and setsockopt() functions. The system documentation should specify the cmsg_type definitions for the supported protocols. Ancillary data is also possible at the socket level. The <sys/socket.h> header defines the following macro for use as the cmsg_type value when cmsg_level is SOL_SOCKET: SCM_RIGHTS Indicates that the data array contains the access rights to be sent or received. The <sys/socket.h> header defines the following macros to gain access to the data arrays in the ancillary data associated with a message header: CMSG_DATA(cmsg) If the argument is a pointer to a cmsghdr structure, this macro returns an unsigned character pointer to the data array associated with the cmsghdr structure. CMSG_NXTHDR(mhdr,cmsg) If the first argument is a pointer to a msghdr structure and the second argument is a pointer to a cmsghdr structure in the ancillary data, pointed to by the msg_control field of that msghdr structure, this macro returns a pointer to the next cmsghdr structure, or a null pointer if this structure is the last cmsghdr in the ancillary data. CMSG_FIRSTHDR(mhdr) If the argument is a pointer to a msghdr structure, this macro returns a pointer to the first cmsghdr structure in the ancillary data associated with this msghdr structure, or a null pointer if there is no ancillary data associated with the msghdr structure. The <sys/socket.h> header defines the linger structure that includes at least the following members: int l_onoff indicates whether linger option is enabled int l_linger linger time, in seconds The <sys/socket.h> header defines the following macros, with distinct integral values: SOCK_DGRAM Datagram socket SOCK_STREAM Byte-stream socket SOCK_SEQPACKET Sequenced-packet socket The <sys/socket.h> header defines the following macro for use as the level argument of setsockopt() and getsockopt(). SOL_SOCKET Options to be accessed at socket level, not protocol level. The <sys/socket.h> header defines the following macros, with distinct integral values, for use as the option_name argument in getsockopt() or setsockopt() calls: SO_ACCEPTCONN Socket is accepting connections. SO_BROADCAST Transmission of broadcast messages is supported. SO_DEBUG Debugging information is being recorded. SO_DONTROUTE bypass normal routing SO_ERROR Socket error status. SO_KEEPALIVE Connections are kept alive with periodic messages. SO_LINGER Socket lingers on close. SO_OOBINLINE Out-of-band data is transmitted in line. SO_RCVBUF Receive buffer size. SO_RCVLOWAT receive «low water mark» SO_RCVTIMEO receive timeout SO_REUSEADDR Reuse of local addresses is supported. SO_SNDBUF Send buffer size. SO_SNDLOWAT send «low water mark» SO_SNDTIMEO send timeout SO_TYPE Socket type. The <sys/socket.h> header defines the following macros, with distinct integral values, for use as the valid values for the msg_flags field in the msghdr structure, or the flags parameter in recvfrom(), recvmsg(), sendto() or sendmsg() calls: MSG_CTRUNC Control data truncated. MSG_DONTROUTE Send without using routing tables. MSG_EOR Terminates a record (if supported by the protocol). MSG_OOB Out-of-band data. MSG_PEEK Leave received data in queue. MSG_TRUNC Normal data truncated. MSG_WAITALL Wait for complete message. The <sys/socket.h> header defines the following macros, with distinct integral values: AF_UNIX UNIX domain sockets AF_UNSPEC Unspecified AF_INET Internet domain sockets The <sys/socket.h> header defines the following macros, with distinct integral values: SHUT_RD Disables further receive operations. SHUT_WR Disables further send operations. SHUT_RDWR Disables further send and receive operations. The following are declared as functions, and may also be defined as macros: int accept(int socket, struct sockaddr *address, socklen_t *address_len); int bind(int socket, const struct sockaddr *address, socklen_t address_len); int connect(int socket, const struct sockaddr *address, socklen_t address_len); int getpeername(int socket, struct sockaddr *address, socklen_t *address_len); int getsockname(int socket, struct sockaddr *address, socklen_t *address_len); int getsockopt(int socket, int level, int option_name, void *option_value, socklen_t *option_len); int listen(int socket, int backlog); ssize_t recv(int socket, void *buffer, size_t length, int flags); ssize_t recvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len); ssize_t recvmsg(int socket, struct msghdr *message, int flags); ssize_t send(int socket, const void *message, size_t length, int flags); ssize_t sendmsg(int socket, const struct msghdr *message, int flags); ssize_t sendto(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len); int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len); int shutdown(int socket, int how); int socket(int domain, int type, int protocol); int socketpair(int domain, int type, int protocol, int socket_vector[2]); SEE ALSO accept(), bind(), connect(), getpeername(), getsockname(), getsockopt(), listen(), recv(), recvfrom(), recvmsg(), send(), sendmsg(), sendto(), setsockopt(), shutdown(), socket(), socketpair(). UNIX ® is a registered Trademark of The Open Group. Copyright © 1997 The Open Group [ Main Index | XSH | XCU | XBD | XCURSES | XNS ]

Изображение баннера

inet_aton

Функция inet_aton конвертирует строку в сетевой адрес. Возвращает int. 1 если конвертация прошла успешно. 0 если конвертация не получилась.

В качестве параметров использует указатель const char и структуру in_addr *addr

Эта функция считается устаревшей, на смену ей пришли inet_pton() и inet_ntop()

Related Posts