IBM Support

Sockets htons, htonl, ntons, and ntohl Functions Cause CPD5D02 Bind Failures in IBM i

Question & Answer


Question

Why does an RPG program fail to build with a binding error for the external procedure 'htons' on IBM i?

Answer

The functions htons, htonl, ntohs, and ntohl are used on platforms that store integers in little‑endian format. These functions perform byte‑swapping to convert integer values from the little‑endian format used on some operating systems to the big‑endian format required for data structures used in sockets programming.

IBM i stores integers in big‑endian format, so none of these functions are needed when writing sockets applications on IBM i. In fact, they are not implemented as callable functions on IBM i at all. They do not exist as exported functions from any service program in the QC2LE binding directory. If you use these functions in an RPGLE program, the program will compile (as long as you provide a function prototype), but the bind step will fail with message CPD5D02. This can be confusing because the equivalent code written in a C or ILE C++ (CLE) program will build without any errors.

The reason for this discrepancy is that these “functions” are actually implemented as macros via #define statements in the <netinet/in.h> header:

 
/*********************************************************************/
 
/* Macros for number representation conversions */
 
/*********************************************************************/
 
#define htonl(qso_htonl) (qso_htonl) /* host byte order to long */
 
#define htons(qso_htons) (qso_htons) /* host byte order to short */
 
#define ntohl(qso_ntohl) (qso_ntohl) /* long to host byte order */
 
#define ntohs(qso_ntohs) (qso_ntohs) /* short to host byte order */
 
 
 

These macros instruct the C preprocessor to replace the “function call” with the parameter that was passed to it. For example:

myuint = htons(port);
 
 
is converted to:
myuint = port;
 
 
before compilation. Because the macro eliminates the function call entirely, no external function needs to be bound, and therefore no bind error occurs in C or C++.

However, in languages such as RPG, which do not use the C preprocessor, the macro substitution does not occur. As a result, including these functions in non‑C source code leads to unresolved external references during the bind step.

Therefore, these functions must be removed from any source code other than C or C++ when building programs on IBM i.

[{"Business Unit":{"code":"BU070","label":"IBM Infrastructure"},"Product":{"code":"SWG60","label":"IBM i"},"Component":["Programming ILE Languages"],"ARM Category":[{"code":"a8m0z0000000CHtAAM","label":"Programming ILE Languages"}],"ARM Case Number":"TS021601708","Line of Business":{"code":"LOB68","label":"Power HW"}}]

Document Information

Modified date:
06 March 2026

UID

ibm17262834