Windows 10 byte order

Сокеты Windows. Порядок байтов Windows Sockets: Byte Ordering

В этой статье и двух сопутствующих статьях объясняются некоторые проблемы, связанные с программированием Windows Sockets. This article and two companion articles explain several issues in Windows Sockets programming. В этой статье описывается порядок байтов. This article covers byte ordering. Другие проблемы описаны в статьях: сокеты Windows: Блокировка и сокеты Windows: преобразование строк. The other issues are covered in the articles: Windows Sockets: Blocking and Windows Sockets: Converting Strings.

Если вы используете или наследуете от класса CAsyncSocket, вам придется самостоятельно управлять этими проблемами. If you use or derive from class CAsyncSocket, you will need to manage these issues yourself. Если вы используете или наследуете от класса CSocket, MFC управляет ими. If you use or derive from class CSocket, MFC manages them for you.

Порядок байтов Byte Ordering

Различные архитектуры компьютеров иногда хранят данные, используя различные порядки байтов. Different machine architectures sometimes store data using different byte orders. Например, компьютеры на базе технологии Intel хранят данные в противоположном порядке компьютеров Macintosh (Motorola). For example, Intel-based machines store data in the reverse order of Macintosh (Motorola) machines. Порядок байтов Intel, называемый прямым порядком байтов, также является обратным по отношению к сетевому стандарту с обратным порядковым порядком байтов. The Intel byte order, called «little-Endian,» is also the reverse of the network standard «big-Endian» order. Эти термины объясняются в следующей таблице. The following table explains these terms.

Упорядоченность больших и Little-Endian байт Big- and Little-Endian Byte Ordering

Порядок байтов Byte ordering Значение Meaning
Big-Endian Big-Endian Наиболее значимый байт находится в левом конце слова. The most significant byte is on the left end of a word.
Little-Endian Little-Endian Наиболее значимый байт находится в правом конце слова. The most significant byte is on the right end of a word.

Как правило, не нужно беспокоиться о преобразовании порядка байтов для данных, отправляемых и получаемых по сети, но существуют ситуации, в которых необходимо преобразовать заказы байтов. Typically, you do not have to worry about byte-order conversion for data that you send and receive over the network, but there are situations in which you must convert byte orders.

Когда необходимо преобразовать порядок байтов When You Must Convert Byte Orders

Порядок байтов необходимо преобразовать в следующих ситуациях: You need to convert byte orders in the following situations:

Вы передаете сведения, которые должны интерпретироваться сетью, а не данные, отправляемые на другой компьютер. You are passing information that needs to be interpreted by the network, as opposed to the data you are sending to another machine. Например, можно передать порты и адреса, которые должны быть понятны сети. For example, you might pass ports and addresses, which the network must understand.

Серверное приложение, с которым вы обмениваетесь данными, не является приложением MFC (и у вас нет исходного кода). The server application with which you are communicating is not an MFC application (and you do not have source code for it). Это вызывает преобразование порядка байтов, если два компьютера не имеют одинаковый порядок байтов. This calls for byte order conversions if the two machines do not share the same byte ordering.

Если не нужно преобразовывать порядок байтов When You Do Not Have to Convert Byte Orders

Вы можете избежать операций преобразования порядка байтов в следующих ситуациях: You can avoid the work of converting byte orders in the following situations:

Компьютеры на обоих концах могут согласиться не менять байты, и оба компьютера используют одинаковый порядок байтов. The machines on both ends can agree not to swap bytes, and both machines use the same byte order.

Сервер, с которым вы обмениваетесь данными, является приложением MFC. The server you are communicating with is an MFC application.

У вас есть исходный код для сервера, с которым вы обмениваетесь данными, поэтому вы можете явно определить, нужно ли преобразовывать побайтовые заказы. You have source code for the server you’re communicating with, so you can tell explicitly whether you must convert byte orders or not.

Сервер можно перенести в MFC. You can port the server to MFC. Это довольно просто, и результат обычно меньше, чем быстрее. This is fairly easy to do, and the result is usually smaller, faster code.

Работая с CAsyncSocket, необходимо самостоятельно управлять любыми необходимыми преобразованиями порядка байтов. Working with CAsyncSocket, you must manage any necessary byte-order conversions yourself. Сокеты Windows стандартизируют модель порядка байтов с обратным порядком следования и предоставляют функции для преобразования между этим заказом и другими. Windows Sockets standardizes the «big-Endian» byte-order model and provides functions to convert between this order and others. Однако CArchive, который используется с CSocket, использует противоположный порядок («с прямым порядком следования байтов)», но CArchive позаботится о преобразованиях порядка байтов. CArchive, however, which you use with CSocket, uses the opposite («little-Endian») order, but CArchive takes care of the details of byte-order conversions for you. Используя это стандартное упорядочение в приложениях или используя функции преобразования порядка следования байтов в Windows Sockets, можно сделать код более переносимым. By using this standard ordering in your applications, or using Windows Sockets byte-order conversion functions, you can make your code more portable.

Идеальным вариантом использования сокетов MFC является ситуация, когда вы пишете оба конца связи: использование MFC на обоих концах. The ideal case for using MFC sockets is when you are writing both ends of the communication: using MFC at both ends. Если вы создаете приложение, которое будет взаимодействовать с приложениями, не использующими MFC, например с FTP-сервером, вам, вероятно, придется самостоятельно управлять обменом байтов перед передачей данных в архивный объект, используя подпрограммы преобразования сокетов Windows нтохс, нтохл, хтонс и хтонл. If you are writing an application that will communicate with non-MFC applications, such as an FTP server, you will probably need to manage byte-swapping yourself before you pass data to the archive object, using the Windows Sockets conversion routines ntohs, ntohl, htons, and htonl. Ниже в этой статье приводятся примеры этих функций, используемых при взаимодействии с приложениями, не использующими MFC. An example of these functions used in communicating with a non-MFC application appears later in this article.

Если другой конец обмена данными не является приложением MFC, необходимо также избегать потоковой передачи объектов C++, производных от, CObject в архив, так как получатель не сможет их обрабатывать. When the other end of the communication is not an MFC application, you also must avoid streaming C++ objects derived from CObject into your archive because the receiver will not be able to handle them. См. Примечание в разделе сокеты Windows: Использование сокетов с архивами. See the note in Windows Sockets: Using Sockets with Archives.

Дополнительные сведения о побайтовых заказах см. в разделе Спецификация сокетов Windows, доступная в Windows SDK. For more information about byte orders, see the Windows Sockets specification, available in the Windows SDK.

Пример преобразования Byte-Order A Byte-Order Conversion Example

В следующем примере показана функция сериализации для CSocket объекта, который использует Архив. The following example shows a serialization function for a CSocket object that uses an archive. Он также иллюстрирует использование функций преобразования порядка байтов в API-интерфейсе Windows Sockets. It also illustrates using the byte-order conversion functions in the Windows Sockets API.

В этом примере представлен сценарий, в котором выполняется запись клиента, взаимодействующего с серверным приложением, не являющимся MFC, для которого отсутствует доступ к исходному коду. This example presents a scenario in which you are writing a client that communicates with a non-MFC server application for which you have no access to the source code. В этом сценарии необходимо предположить, что сервер, не являющийся сервером MFC, использует стандартный сетевой порядок байтов. In this scenario, you must assume that the non-MFC server uses standard network byte order. В отличие от этого, клиентское приложение MFC использует CArchive объект с CSocket объектом и CArchive использует порядок байтов с прямым порядком следования, противоположный стандарту сети. In contrast, your MFC client application uses a CArchive object with a CSocket object, and CArchive uses «little-Endian» byte order, the opposite of the network standard.

Предположим, что сервер, не относящийся к MFC, с которым планируется обмениваться данными, имеет установленный протокол для пакета сообщений, который выглядит следующим образом: Suppose the non-MFC server with which you plan to communicate has an established protocol for a message packet like the following:

В терминах MFC это выражение выражается следующим образом: In MFC terms, this would be expressed as follows:

В C++, по struct сути, это то же самое, что и класс. In C++, a struct is essentially the same thing as a class. Message Структура может иметь функции элементов, например Serialize функцию члена, объявленную выше. The Message structure can have member functions, such as the Serialize member function declared above. Serialize Функция члена может выглядеть следующим образом: The Serialize member function might look like this:

В этом примере вызывается преобразование порядка байтов данных, так как существует четкое несоответствие порядка байтов серверного приложения, не относящегося к MFC, на одном конце и CArchive используемого в клиентском приложении MFC на другом конце. This example calls for byte-order conversions of data because there is a clear mismatch between the byte ordering of the non-MFC server application on one end and the CArchive used in your MFC client application on the other end. В примере показаны некоторые функции преобразования порядка байтов, предоставляемые сокетами Windows. The example illustrates several of the byte-order conversion functions that Windows Sockets supplies. Эти функции описаны в следующей таблице. The following table describes these functions.

Функции преобразования Byte-Order сокеты Windows Windows Sockets Byte-Order Conversion Functions

Функция Function Назначение Purpose
нтохс ntohs Преобразование 16-разрядного количества из сетевого байтового порядка в порядок размещения байтов (с обратным порядком байтов (Big-endian). Convert a 16-bit quantity from network byte order to host byte order (big-Endian to little-Endian).
нтохл ntohl Преобразование 32-разрядного количества из сетевого байтового порядка в порядковый номер размещения в байтах (с обратным порядком байтов). Convert a 32-bit quantity from network byte order to host byte order (big-Endian to little-Endian).
хтонс Htons Преобразует 16-разрядное количество из байтового порядка узла в сетевой байтовый порядок (с прямым порядком байтов с обратным порядком байтов). Convert a 16-bit quantity from host byte order to network byte order (little-Endian to big-Endian).
хтонл Htonl Преобразование 32-разрядного количества из байтового порядка узла в сетевой байтовый порядок (с прямым порядком байтов с обратным порядком байтов). Convert a 32-bit quantity from host byte order to network byte order (little-Endian to big-Endian).

Еще одной точкой этого примера является то, что если приложение сокета на другом конце связи является приложением, не являющимся MFC, необходимо избегать выполнения следующих действий: Another point of this example is that when the socket application on the other end of the communication is a non-MFC application, you must avoid doing something like the following:

где pMsg — указатель на объект C++, производный от класса CObject . where pMsg is a pointer to a C++ object derived from class CObject . При этом будут отправлены дополнительные сведения MFC, связанные с объектами, и сервер не сможет понять его, как если бы он был приложением MFC. This will send extra MFC information associated with objects and the server will not understand it, as it would if it were an MFC application.

Дополнительные сведения см. в разделе: For more information, see:

Byte Ordering

Care must always be taken to account for any differences between the byte ordering used for storing integers by the host architecture and the byte ordering used on the wire by individual transport protocols. Any reference to an address or port number passed to or from a Windows Sockets routine must be in the network order (big-endian) for the protocol being utilized. In the case of IP, this includes the IP address and port parameters of a sockaddr structure (but not the sin_family parameter).

A number of the UNIX systems operate on CPUs that represent integers in network byte order (big-endian). So the need to convert integers from host byte order to network byte order can be ignored without causing problems even if this is not recommended for portability.

In contrast, the byte ordering used to represent integers by most IntelВ® CPUs is little-endian. So it is becomes mandatory that integers be converted from host byte-order to network byte order before being used in Winsock Sockets functions and structures.

Consider an application that normally contacts a server on the TCP port corresponding to the time service, but provides a mechanism for the user to specify an alternative port. The port number returned by getservbyname is already in network order, which is the format required for constructing an address so that no translation is required. However, if the user elects to use a different port, entered as an integer, the application must convert this from host to TCP/IP network order (using the htons or WSAHtons function) before using it to construct an address. Conversely, if the application were to display the number of the port within an address (returned by getpeername for example), the port number must be converted from network to host order (using the ntohs or WSANtohs function) before it can be displayed.

Since the Intel and Internet byte orders are different, the conversions described in the preceding are unavoidable. Application writers are cautioned that they should use the standard conversion functions provided as part of Winsock rather than writing their own conversion code since future implementations of Winsock are likely to run on systems for which the host order is identical to the network byte order. Only applications that use the standard conversion functions between host and network byte order are likely to be portable.

Читайте также:  Как открыть под линукс
Оцените статью