5G NGAP C Sample Code Using OSS ASN.1 Tools


This sample is provided as part of the OSS ASN.1 Tools trial and commercial shipments. The source code and related files are listed below for reference.

The sample demonstrates how to use the OSS ASN.1 Tools to process messages for the 3GPP 5G NGAP standard (TS 38.413 version 19.0.0).

It runs on Linux on x86-64 as an example and illustrates how to decode, inspect, and create PER-encoded 5G NGAP messages using the OSS ASN.1 Tools API.

The sample reads NGAP messages from .per files, decodes and prints them, and creates and encodes a response message.

A makefile is included for building and running the test program using the OSS ASN.1/C runtime.

To explore more samples (LTE RRC, 5G RRC, S1AP, X2AP, NGAP), visit the main Sample Code page.

Overview

This sample shows how to:

  • Initialize the OSS ASN.1/C runtime for the 5G NGAP schema.
  • Read .per files that contain valid PER-encoded 5G NGAP messages.
  • Decode and print 5G NGAP messages.
  • Create and encode a response message.
  • Build and run the sample test program with a makefile on Linux.

Files in This Sample

The files listed below are included in the OSS ASN.1 Tools trial and commercial shipments and are used by this sample program:

File Description
README.TXT Instructions and sample overview.
*.asn ASN.1 source files that describe the 3GPP 5G NGAP protocol (TS 38.413) used with this program example.
NGAP-PDU_HandoverRequest.per Valid PER-encoded NGAP message. It should pass testing.
tngap.c Simple C program that shows how to work with 5G NGAP protocol data. It reads input messages from files, decodes and prints them, and creates and encodes a response message.
makefile Makefile that builds and runs the sample test.
makefile.rtoed Makefile that builds and runs the sample test using RTOED.
gui/ ASN.1 Studio project for viewing/compiling schema and generating sample data.

Build and Run Instructions

(Installation instructions for the OSS ASN.1 Tools are included in all trial and commercial shipments.)

To build and run this sample, install a trial or licensed version of the OSS ASN.1 Tools for C.

1. Generate C source and header files (runtime-only shipments)

If your shipment is runtime-only, generate the .c and .h files by running:

make cross

This creates a samples/cross directory with:

  • the required .asn files
  • scripts to run the OSS ASN.1/C compiler (asn1cpl.sh or asn1cpl.bat)
2. Build and run the sample
make

This command compiles the sample C source, links it with the OSS ASN.1 static library, and executes the test. To use another type of library in the shipment (such as a shared library), set the A makefile variable, for example:

make A=so
3. Clean up generated files
make clean
4. Other Platforms

Note: The C source code in this sample is platform-independent. Linux commands are shown as an example, but equivalent samples and build instructions are available for Windows, macOS, and other platforms. For help with platform-specific instructions, please contact OSS Support.

Code Listing: tngap.c

The following listing shows the main C source file for this sample test program, tngap.c. It demonstrates how to read PER-encoded 5G NGAP messages from files, decode and print them, and create and encode a response message using the OSS ASN.1 Tools API.

Show tngap.c source code
/*****************************************************************************/
/*  Copyright (C) 2025 OSS Nokalva, Inc.  All rights reserved.               */
/*****************************************************************************/
/* THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC.                    */
/* AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC.             */
/* THIS FILE MAY NOT BE DISTRIBUTED.                                         */
/* THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED.                              */
/* THIS SAMPLE PROGRAM IS PROVIDED AS IS. THE SAMPLE PROGRAM AND ANY RESULTS */
/* OBTAINED FROM IT ARE PROVIDED WITHOUT ANY WARRANTIES OR REPRESENTATIONS,  */
/* EXPRESS, IMPLIED OR STATUTORY.                                            */
/*****************************************************************************/
/*
 * $Id: 5G-ngap-c.html 3363 2026-02-16 09:51:05Z macra $
 */

/*
 *Demonstrates work with data for NGAP protocol
 */

#include <errno.h>
#include <string.h>
#include "ngap_r19.h"

/* Names of Criticality values */
static const char *Criticalities[] = { "reject", "ignore", "notify" };

/* Names of HandoverType values */
static const char *HandoverType[] = {
	"intra5gs", "fivegs-to-eps", "eps-to-5gs", "unknown"
};

/* The directory where input files reside. It is set to the command line parameter
 * if any and to the directory where the sample is started, otherwise.
 */
char *filesDir;

/*
 * FUNCTION     reportError() prints error message and error code returned
 *              by any runtime API function.
 *
 * PARAMETERS
 *     world    OSS environment variable
 *     where    error origin
 *     errcode  error code
 *     errmsg   error message or NULL if ossGetErrMsg() should be used
 *              to get it
 *
 * RETURNS      errcode
 */
static int reportError(OssGlobal *world, const char *where,
				    int errcode, const char *errmsg)
{
    /* Error occured */
    if (errcode) {
        ossPrint(world, "%s failed, error code: %d\n", where, errcode);
	/* Get and print error message */
	if (errmsg || (world && NULL != (errmsg = ossGetErrMsg(world))))
	    ossPrint(world, "Error text: %s\n", errmsg);
    }
    return errcode;
}

/*
 * FUNCTION     Helper function to open file in the specified directory.
 *
 * PARAMETERS
 *     world            OSS environment variable
 *     directoryName    directory where fileName resides
 *     fileName         file to open
 *
 * RETURNS      pointer to file on success, NULL on failure
 */
FILE * openInputFile(OssGlobal *world, char *directoryName, const char *fileName)
{
    char *path;
    FILE *fv;
    const char kPathSeparator =
#ifdef _WIN32
				'\\';
#else
				'/';
#endif

    if (directoryName) {
	size_t dLength = strlen(directoryName);

	if (NULL == (path = ossGetMemory(world, dLength + strlen(fileName) + 2))) {
	    return NULL;
	}

	memcpy(path, directoryName, dLength);
	if (path[dLength - 1] != kPathSeparator)
	    path[dLength++] = kPathSeparator;
	strcpy(path+dLength, fileName);
    } else {
	path = (char *) fileName;
    }

    if (!(fv = fopen(path, "rb"))) {
	ossPrint(world, "Failed to open the '%s' file. Restart the sample program using the file "
		"location as the input parameter.\n", path);
    }

    if (path != fileName)
	ossFreeMemory(world, path);

    return fv;
}

/*
 * FUNCTION     readEncodingFromFile() reads serialized message from specified
 *              file
 *
 * PARAMETERS
 *    world     OSS environment variable
 *    filename  name of file containing serialized message
 *    encoding  read message
 *
 * RETURNS      0 on success, error code on failure
 */
static int readEncodingFromFile(OssGlobal *world,
				    const char *filename, OssBuf *encoding)
{
    FILE        *in = openInputFile(world, filesDir, filename);
    long        length;
    unsigned char *data;

    if (!in)
	return reportError(world, "fopen()", errno, strerror(errno));

    if (fseek(in, 0, SEEK_END))
	return reportError(world, "fseek()", errno, strerror(errno));

    length = ftell(in);
    if (length < 0)
	return reportError(world, "ftell()", errno, strerror(errno));

    /* Allocate memory to store completely read message in it */
    data = ossGetMemory(world, (size_t)length);
    if (!data) {
	reportError(world, "ossGetMemory()", OUT_MEMORY, NULL);
	fclose(in);
	return OUT_MEMORY;
    }
    rewind(in);

    if ((size_t)length != fread(data, sizeof(char), (size_t)length, in))
	return reportError(world, "fread()", 1, NULL);
    fclose(in);
    /* Store read message in output argument */
    encoding->value = data;
    encoding->length = (size_t)length;
    return 0;
}


/*****************************************************************************
 * Printing functions below are intended to demonstrate how to access NGAP
 * PDU components and to analyze their contents.
 *****************************************************************************/

/*
 * FUNCTION     printHexString() prints data (octet string) as a sequence of
 *              hexadecimal digits 'XXXX...'H
 *
 * PARAMETERS
 *    world     OSS environment variable
 *    length    length of input data
 *    value     pointer to input data
 *    indent    indentation
 *
 * RETURNS      0 on success, error code on failure
 */
static int printHexString(OssGlobal *world,
		unsigned int length, unsigned char *value, int indent)
{
    unsigned int i, j,
		max_pos = 74 - indent;

    ossPrint(world, "'");
    for (i = 0, j = 1; i < length; i++, j += 2) {
	/* skip to next line when the current one is filled */
	if (j >= max_pos) {
	    ossPrint(world, "'\n%*s'", indent, "");
	    j = 1;
	}
	ossPrint(world, "%02X", value[i]);
    }
    ossPrint(world, "'H");
    return 0;
}

/* Prints a BIT STRING as a sequence of hexadecimal digits */
#define printHexBitString(ctx, length, value, indent) \
	    printHexString(ctx, (length + 7)/8, value, indent)

/*
 * FUNCTION     printProtocolExtensions() prints ProtocolExtensionContainer
 *              data. ossPrintPDU() is called to print PDU stored in
 *              an OpenType value.
 *
 * PARAMETERS
 *    world     OSS environment variable
 *    ie_ext    pointer to ProtocolExtensionContainer data to print
 *    indent    indentation
 *
 * RETURNS      0 on success, error code on failure
 */
static int printProtocolExtensions(OssGlobal *world, struct OSS_NGAP_ProtocolExtensionContainer_ *ie_ext,
				int indent)
{
    size_t      i;

    ossPrint(world, "%*s%s includes the following IEs:\n", indent++, "",
				"iE-Extensions");
    /* Print each IE in the list */
    for (i = 1; ie_ext; ie_ext = ie_ext->next, i++) {
	OSS_NGAP_OverloadStopIEs_Value *extval = &ie_ext->value.extensionValue;

	ossPrint(world, "%*s#%d: id = %2u, criticality = %s\n", indent, "",
		i, ie_ext->value.id, Criticalities[ie_ext->value.criticality]);
	if (extval->pduNum && extval->decoded.other.pdu_NGAP_PDU)
	    ossPrintPDU(world, extval->pduNum, extval->decoded.other.pdu_NGAP_PDU);
	else
	    ossPrint(world, "PDU is not decoded\n");
    }
    return 0;
}

/*
 * FUNCTION     printProtocolIEs() prints ProtocolIE_Container data.
 *              ossPrintPDU() is called to print IEs that are not
 *              handled by this function.
 *
 * PARAMETERS
 *    world     OSS environment variable
 *    pdu       input NGAP PDU which data should be printed
 *    ies       pointer to ProtocolIE-Container data to print
 *    indent    indentation
 *
 * RETURNS      0 on success, error code on failure
 */
static int printProtocolIEs(OssGlobal *world, struct OSS_NGAP_HRequiredIEs *ies, int indent)
{
    int err = 0;
    int      i;

    ossPrint(world, "%*s%s includes the following IEs:\n", indent++, "",
					"protocolIEs");
    /* Print each IE */
    for (i = 1; ies; ies = ies->next, i++) {
	struct OSS_NGAP_HRequiredIE *field = &ies->value;

	ossPrint(world, "\n%*s#%d: id = %2u, criticality = %s\n", indent, "",
		    i, field->id, Criticalities[field->criticality]);

	++indent;
        if (field->id == OSS_NGAP_id_AMF_UE_NGAP_ID) {
	    ossPrint(world, "%*svalue %s: " ULLONG_FMT "\n", indent, "", "AMF-UE-NGAP-ID",
					*field->value.decoded.pdu_AMF_UE_NGAP_ID);
	} else if (field->id == OSS_NGAP_id_RAN_UE_NGAP_ID) {
	    ossPrint(world, "%*svalue %s: %u\n", indent, "", "RAN-UE-NGAP-ID",
					*field->value.decoded.pdu_RAN_UE_NGAP_ID);
	} else 	if (field->id == OSS_NGAP_id_HandoverType) {
	    ossPrint(world, "%*svalue %s: %s\n", indent, "", "HandoverType",
		HandoverType[
			((*field->value.decoded.pdu_HandoverType) <= OSS_NGAP_eps_to_5gs)
			    ? *field->value.decoded.pdu_HandoverType : OSS_NGAP_eps_to_5gs + 1]);
	} else if (field->id == OSS_NGAP_id_Cause) {
	    OSS_NGAP_Cause  *pcause = field->value.decoded.pdu_Cause;

	    /*
	     * Named values can be printed below instead of numbers for all
	     * Cause components
	     */
	    ossPrint(world, "%*svalue %s: ", indent, "", "Cause");

	    switch (pcause->choice) {
	    case OSS_NGAP_radioNetwork_chosen:
		ossPrint(world, "%s : %d", "radioNetwork",
						pcause->u.radioNetwork);
		break;
	    case OSS_NGAP_transport_chosen:
		ossPrint(world, "%s : %d", "transport", pcause->u.transport);
		break;
	    case OSS_NGAP_nas_chosen:
		ossPrint(world, "%s : %d", "nas", pcause->u.nas);
		break;
	    case OSS_NGAP_protocol_chosen:
		ossPrint(world, "%s : %d", "protocol", pcause->u.protocol);
		break;
	    case OSS_NGAP_misc_chosen:
		ossPrint(world, "%s : %d", "misc", pcause->u.misc);
		break;
	    case OSS_NGAP_Cause_choice_Extensions_chosen:
		ossPrint(world, "%s: ", "choice-Extensions --<Not implemented>--");
		break;
	    }
	    ossPrint(world, "\n");
	/* TargetID IE */
	} else if (field->id == OSS_NGAP_id_TargetID) {
	    OSS_NGAP_TargetID *ptarget = field->value.decoded.pdu_TargetID;

	    ossPrint(world, "%*svalue %s : ", indent, "", "TargetID");
	    indent++;
	    switch (ptarget->choice) {
	    case OSS_NGAP_targetRANNodeID_chosen: {
		OSS_NGAP_TargetRANNodeID *targeteRN_ID = &ptarget->u.targetRANNodeID;

		ossPrint(world, "%s :\n", "globalRANNodeID");
		indent++;
		switch (targeteRN_ID->globalRANNodeID.choice) {
		case OSS_NGAP_globalGNB_ID_chosen: {
		    OSS_NGAP_GlobalGNB_ID *glob_id = &targeteRN_ID->globalRANNodeID.u.globalGNB_ID;

		    ossPrint(world, "%*s%s:\n", indent, "", "globalGNB-ID");
		    indent++;
		    ossPrint(world, "%*s%s: ", indent, "", "pLMNIdentity");
		    printHexString(world, sizeof(glob_id->pLMNIdentity),
				    glob_id->pLMNIdentity, indent);

		    ossPrint(world, "\n%*s%s : ", indent, "", "gNB-ID");
		    switch (glob_id->gNB_ID.choice) {
			case OSS_NGAP_gNB_ID_chosen:
			    ossPrint(world, "%s: ", "gNB-ID");
			    printHexBitString(world, glob_id->gNB_ID.u.gNB_ID.length,\
				    glob_id->gNB_ID.u.gNB_ID.value, indent);
			    break;
			case OSS_NGAP_GNB_ID_choice_Extensions_chosen:
			    ossPrint(world, "%s: ", "choice-Extensions --<Not implemented>--");
			    break;
		    }
		    ossPrint(world, "\n");
		    if (glob_id->bit_mask & OSS_NGAP_GlobalGNB_ID_iE_Extensions_present) {
			printProtocolExtensions(world, glob_id->iE_Extensions, indent);
			ossPrint(world, "\n");
		    }
		    indent--;
		    break;
		}
		case OSS_NGAP_globalNgENB_ID_chosen: {
		    /* targeteRN_ID->globalRANNodeID.u.globalNgENB_ID; */
		    ossPrint(world, "%s :\n", "globalNgENB-ID --<Not implemented>--\n");
		    break;
		}
		case OSS_NGAP_globalN3IWF_ID_chosen: {
		    ossPrint(world, "%s :\n", "globalN3IWF-ID --<Not implemented>--\n");
		    /* targeteRN_ID->globalRANNodeID.u.globalN3IWF_ID; */
		    break;
		}
		case OSS_NGAP_GlobalRANNodeID_choice_Extensions_chosen:
		    ossPrint(world, "%s: ", "choice-Extensions --<Not implemented>--\n");
		}
		ossPrint(world, "%*s%s:\n", indent, "", "selectedTAI");
		indent++;
		ossPrint(world, "%*s%s: ", indent, "", "pLMNIdentity");
		printHexString(world, sizeof(targeteRN_ID->selectedTAI.pLMNIdentity),
				    targeteRN_ID->selectedTAI.pLMNIdentity, indent);
		ossPrint(world, "\n%*s%s: ", indent, "", "tAC");
		printHexString(world, sizeof(targeteRN_ID->selectedTAI.tAC),
				    targeteRN_ID->selectedTAI.tAC, indent);
		if (targeteRN_ID->bit_mask & OSS_NGAP_TargetRANNodeID_iE_Extensions_present) {
		    ossPrint(world, "\n");
		    printProtocolExtensions(world, (struct OSS_NGAP_ProtocolExtensionContainer_ *)targeteRN_ID->iE_Extensions, indent);
		}
		indent -= 2;
		break;
	    }
	    case OSS_NGAP_targeteNB_ID_chosen: {
		OSS_NGAP_TargeteNB_ID  *targeteNB_ID = &ptarget->u.targeteNB_ID;

		ossPrint(world, "\n%*s%s: ", indent, "", "globalENB-ID");
		ossPrint(world, "\n%*s%s: ", indent, "", "selected-EPS-TAI");
		if (targeteNB_ID->bit_mask & OSS_NGAP_TargeteNB_ID_iE_Extensions_present) {
		    ossPrint(world, "\n");
		    printProtocolExtensions(world, targeteNB_ID->iE_Extensions, indent);
		}
		break;
	    }
	    case OSS_NGAP_TargetID_choice_Extensions_chosen:
		ossPrint(world, "%s: ", "choice-Extensions --<Not implemented>--");
		break;
	    }

	    indent--;
	    ossPrint(world, "\n");
	} else if (field->id == OSS_NGAP_id_DirectForwardingPathAvailability) {
	    OSS_NGAP_DirectForwardingPathAvailability *ptarget =
				field->value.decoded.pdu_DirectForwardingPathAvailability;

	    ossPrint(world, "%*svalue %s : ", indent, "", "DirectForwardingPathAvailability");
	    if (*ptarget)
		ossPrint(world,	"%u\n", *ptarget);
	    else
		ossPrint(world, "direct-path-available\n");
	} else if (field->id == OSS_NGAP_id_PDUSessionResourceListHORqd) {
	    ossPrint(world, "%*svalue %s : ", indent, "", "PDUSessionResourceListHORqd");
	    ossPrint(world, "%*s%s : ", indent + 1, "--<Not implemented>--\n");
	} else if (field->id == OSS_NGAP_id_SourceToTarget_TransparentContainer) {
	    OSS_NGAP_SourceToTarget_TransparentContainer *ptarget =
			    field->value.decoded.pdu_SourceToTarget_TransparentContainer;

	    ossPrint(world, "%*svalue %s : ", indent, "", "SourceToTarget-TransparentContainer");
	    printHexString(world, ptarget->length, ptarget->value, indent);
	    ossPrint(world, "\n");
	} else
	    ossPrint(world, "%*svalue %s (%d)\n", indent, "", "UNKNOWN", field->id);
	indent--;
    }
    return err;
}

/*
 * FUNCTION     printHandoverRequiredMsg() prints NGAP pdu which contains
 *              HandoverRequired message.  The function is not intended to
 *              handle other types of messages.
 *
 * PARAMETERS
 *    world     OSS enviroonment variable
 *    pdu       input NGAP PDU which data should be printed
 *
 * RETURNS      0 on success, error code on failure
 */
static int printHandoverRequiredMsg(OssGlobal *world, OSS_NGAP_PDU *pdu)
{
    int         msg_id;
    OSS_NGAP_NGAP_ELEMENTARY_PROCEDURES_InitiatingMessage  *msg_value;
    OSS_NGAP_HandoverRequired	*hr_value;

    /* Get identifier of message stored in PDU */
    if (pdu->choice != OSS_NGAP_initiatingMessage_chosen) {
	ossPrint(world, "Unexpected type of message");
	return -1;
    }

    msg_value = &pdu->u.initiatingMessage.value;
    msg_id = msg_value->pduNum;
    if ( msg_id != OSS_NGAP_HandoverRequired_PDU) {
	ossPrint(world, "Unexpected message id = %d\n", msg_id);
	return -1;
    } else {
	hr_value = msg_value->decoded.pdu_HandoverRequired;
    }

    ossPrint(world, "Message id = %d (HandoverRequired)\n\n", msg_id);

    if (!hr_value || !hr_value->protocolIEs) {
        ossPrint(world, "Incorrect message \n");
        return -1;
    }

    return printProtocolIEs(world, hr_value->protocolIEs, 0);
}

/*
 * FUNCTION     createSuccessResponse() creates NGAP successful outcome
 *              message for given HandoverRequired request.
 *
 * PARAMETERS
 *    world     OSS environment variable
 *    req       input message (request)
 *    resp      pointer to the successful outcome message (response)
 *              created by the function
 *
 * RETURNS      0 on success, error code on failure
 */
static int createSuccessResponse(OssGlobal *world, OSS_NGAP_PDU *req,
							    OSS_NGAP_PDU **resp)
{
    OSS_NGAP_HandoverRequired  *hr_value;
    OSS_NGAP_SuccessfulOutcome *outcome_msg;
    OSS_NGAP_NGAP_ELEMENTARY_PROCEDURES_SuccessfulOutcome *ot_val;
    struct OSS_NGAP_HRequiredIEs *reqies;
    struct OSS_NGAP_HCommandIEs *respies;
    ossBoolean	element_was_found;;

    if (req->choice != OSS_NGAP_initiatingMessage_chosen) {
	ossPrint(world, "Unexpected type of message");
	return -1;
    }

    if (req->u.initiatingMessage.value.pduNum == 0
	|| req->u.initiatingMessage.value.encoded.value) {
	ossPrint(world, "Unexpected HandoverRequired request data");
	return -1;
    }

    hr_value = req->u.initiatingMessage.value.decoded.pdu_HandoverRequired;

    if (NULL == (reqies = hr_value->protocolIEs)) {
	ossPrint(world, "No IEs in HandoverRequired request");
	return -1;
    }

    /*
     * Create successful outcome message from initiating message. Copy
     * some IEs from input to output.
     */
    *resp = ossGetInitializedMemory(world, sizeof(OSS_NGAP_PDU));
    if (!*resp)
	return reportError(world, "ossGetInitializedMemory for OSS_NGAP_PDU",
			OUT_MEMORY, NULL);

    (*resp)->choice = OSS_NGAP_successfulOutcome_chosen;

    outcome_msg = &(*resp)->u.successfulOutcome;
    outcome_msg->procedureCode = req->u.initiatingMessage.procedureCode;
    outcome_msg->criticality = OSS_NGAP_reject;

    ot_val = &outcome_msg->value;
    ot_val->pduNum = OSS_NGAP_HandoverCommand_PDU;
    ot_val->decoded.pdu_HandoverCommand =
	ossGetInitializedMemory(world, sizeof(OSS_NGAP_HandoverCommand));
    if (!ot_val->decoded.pdu_HandoverCommand) {
	/* Deallocate OSS_NGAP_PDU on error */
	ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
	return reportError(world, "ossGetInitializedMemory for OSS_NGAP_HandoverCommand",
			OUT_MEMORY, NULL);
    }

    ot_val->decoded.pdu_HandoverCommand->protocolIEs =
			ossGetInitializedMemory(world, sizeof(struct OSS_NGAP_HCommandIEs));
    if (NULL == (respies = ot_val->decoded.pdu_HandoverCommand->protocolIEs)) {
	/* Deallocate OSS_NGAP_PDU on error */
	ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
	return reportError(world, "ossGetInitializedMemory for OSS_NGAP_ProtocolIE_Container",
			OUT_MEMORY, NULL);
    }

    for (element_was_found = FALSE; reqies; reqies = reqies->next) {
	if (reqies->value.id == OSS_NGAP_id_AMF_UE_NGAP_ID
	    || reqies->value.id == OSS_NGAP_id_RAN_UE_NGAP_ID
	    || reqies->value.id == OSS_NGAP_id_HandoverType
	    || reqies->value.id == OSS_NGAP_id_SourceToTarget_TransparentContainer) {
	    if (element_was_found) {
    		respies->next = ossGetInitializedMemory(world,
					sizeof(struct OSS_NGAP_HCommandIEs));
    		if (!respies->next) {
		    /* Deallocate OSS_NGAP_PDU on error */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
		    return reportError(world, "ossGetInitializedMemory for OSS_NGAP_ProtocolIE_Container",
				OUT_MEMORY, NULL);
		}
	        respies = respies->next;
	    }
	    if (reqies->value.id == OSS_NGAP_id_AMF_UE_NGAP_ID) {
	        respies->value.value.decoded.pdu_AMF_UE_NGAP_ID =
	    			ossGetInitializedMemory(world, sizeof(OSS_NGAP_AMF_UE_NGAP_ID));
	    	if (!respies->value.value.decoded.pdu_AMF_UE_NGAP_ID) {
		    /* Deallocate OSS_NGAP_PDU on error */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
		    return reportError(world, "ossGetInitializedMemory for OSS_NGAP_AMF_UE_NGAP_ID",
				OUT_MEMORY, NULL);
		}
		respies->value.value.pduNum = OSS_NGAP_PDU_HandoverCommandIEs_Value_AMF_UE_NGAP_ID;
	        *respies->value.value.decoded.pdu_AMF_UE_NGAP_ID =
				*reqies->value.value.decoded.pdu_AMF_UE_NGAP_ID;
	    } else if (reqies->value.id == OSS_NGAP_id_RAN_UE_NGAP_ID) {
	        respies->value.value.decoded.pdu_RAN_UE_NGAP_ID =
	    			ossGetInitializedMemory(world, sizeof(OSS_NGAP_RAN_UE_NGAP_ID));
	    	if (!respies->value.value.decoded.pdu_RAN_UE_NGAP_ID) {
		    /* Deallocate OSS_NGAP_PDU on error */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
		    return reportError(world, "ossGetInitializedMemory for OSS_NGAP_RAN_UE_NGAP_ID",
				OUT_MEMORY, NULL);
		}
		respies->value.value.pduNum = OSS_NGAP_PDU_HandoverCommandIEs_Value_RAN_UE_NGAP_ID;
	        *respies->value.value.decoded.pdu_RAN_UE_NGAP_ID =
				*reqies->value.value.decoded.pdu_RAN_UE_NGAP_ID;
	    } else if (reqies->value.id == OSS_NGAP_id_HandoverType) {
	        respies->value.value.decoded.pdu_HandoverType =
	    			ossGetInitializedMemory(world, sizeof(OSS_NGAP_HandoverType));
	    	if (!respies->value.value.decoded.pdu_HandoverType) {
		    /* Deallocate OSS_NGAP_PDU on error */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
		    return reportError(world, "ossGetInitializedMemory for OSS_NGAP_HandoverType",
				OUT_MEMORY, NULL);
		}
		respies->value.value.pduNum = OSS_NGAP_PDU_HandoverCommandIEs_Value_HandoverType;
	        *respies->value.value.decoded.pdu_HandoverType =
				*reqies->value.value.decoded.pdu_HandoverType;
	    } else {
		/*
		 * Create TargetToSource_TransparentContainer.
		 * Now copy SourceToTarget_TransparentContainer to Target.
		 */
		OSS_NGAP_TargetToSource_TransparentContainer *t2s_container;
		OSS_NGAP_SourceToTarget_TransparentContainer *s2t_container =
				reqies->value.value.decoded.pdu_SourceToTarget_TransparentContainer;

	        t2s_container = ossGetInitializedMemory(world, sizeof(OSS_NGAP_TargetToSource_TransparentContainer));
	    	if (!t2s_container) {
		    /* Deallocate OSS_NGAP_PDU on error */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
		    return reportError(world, "ossGetInitializedMemory for OSS_NGAP_TargetToSource_TransparentContainer",
				OUT_MEMORY, NULL);
		}
		respies->value.value.decoded.pdu_TargetToSource_TransparentContainer = t2s_container;
		respies->value.value.pduNum = OSS_NGAP_PDU_HandoverCommandIEs_Value_TargetToSource_TransparentContainer;
	        t2s_container->length = s2t_container->length;
	        t2s_container->value = ossGetMemory(world, t2s_container->length);
	    	if (!t2s_container->value) {
		    /* Deallocate OSS_NGAP_PDU on error */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, *resp);
		    return reportError(world, "ossGetMemory for OSS_NGAP_TargetToSource_TransparentContainer",
				OUT_MEMORY, NULL);
		}
		memcpy(t2s_container->value, s2t_container->value, s2t_container->length);
	    }
	    if (reqies->value.id == OSS_NGAP_id_SourceToTarget_TransparentContainer)
		respies->value.id = OSS_NGAP_id_TargetToSource_TransparentContainer;
	    else
 		respies->value.id = reqies->value.id;
	    element_was_found = TRUE;
	}
    }

    return 0;
}

/*
 * FUNCTION     testNGAP() is used to test NGAP message, the input serialized
 *              pdu is deserialized and printed, then an outcome message
 *              is created, printed and encoded.
 *
 * PARAMETERS
 *    world	OSS environment variable
 *    filename  name of file containing serialized message
 *
 * RETURNS      0 on success, error code on failure
 */
static int testNGAP(OssGlobal *world, const char *filename)
{
    OssBuf	encoded_data;
    int		err, pdu_num = OSS_NGAP_PDU_PDU;

    ossPrint(world, "======================================================"
		"======================\n");
    ossPrint(world, "### Reading serialized request message from file: \"%s\"... ", filename);
    /* Read serialized message from file */
    err = readEncodingFromFile(world, filename, &encoded_data);
    if (!err) {
	OSS_NGAP_PDU    *req = NULL;

	ossPrint(world, "OK.\n\n");
	/*
	 * Zero deserilaized message pointer in order to allocate it
	 * in API call
	 */
	ossPrint(world, "### Deserializing the message...\n");
	/* Deserialize input message */
	err = ossDecode(world, &pdu_num, &encoded_data, (void**)&req);
        ossPrint(world, "\n");
	/* Print error diagnostics if an error takes place */
	if (err) {
	    reportError(world, "ossDecode()", err, NULL);
	} else {
	    ossPrint(world, "### Printing the deserialized message by ossPrintPDU():\n");
	    /* Print deserialized message */
	    err = ossPrintPDU(world, OSS_NGAP_PDU_PDU, req);
	    ossPrint(world, "\n");
	    if (err) {
		reportError(world, "ossPrintPDU()", err, NULL);
		if (req)
		/* Deallocate input message */
		    ossFreePDU(world,  OSS_NGAP_PDU_PDU, req);
		return err;
	    }
	    ossPrint(world, "### Printing the deserialized message by a handwritten code"
		    " demonstrating how to access data:\n");
	    if (0 == (err = printHandoverRequiredMsg(world, req))) {
		OSS_NGAP_PDU    *resp;

		ossPrint(world, "\n### Creating Success Response message... ");
		/* Create successful outcome message */
		err = createSuccessResponse(world, req, &resp);
		if (!err) {
		    OssBuf     msg = { 0, NULL };

		    ossPrint(world, "OK.\n\n### Printing the created responce message by ossPrintPDU():\n");
		    err = ossPrintPDU(world, OSS_NGAP_PDU_PDU, resp);
		    ossPrint(world, "\n");
		    ossPrint(world, "\n### Serializing the response message... \n");
		    /* Serialize outcome message */
		    err = ossEncode(world, OSS_NGAP_PDU_PDU, resp, &msg);
		    ossPrint(world, "\n");
		    if (err) {
			reportError(world, "ossEncode()", err, NULL);
		    /* Print serialized outcome message */
		    } else {
			ossPrint(world, "Serialized response (%ld bytes):\n",
				    msg.length);
			printHexString(world, msg.length, msg.value, 0);
			ossFreeMemory(world, msg.value);
			ossPrint(world, "\n\n");
		    }
		    /* Free memory allocated for outcome message */
		    ossFreePDU(world, OSS_NGAP_PDU_PDU, resp);
		}
	    }
	}
	/*
	 * Free memory allocated for input message if it is deserialized
	 * successfully
	 */
	if (req)
	    ossFreePDU(world, OSS_NGAP_PDU_PDU, req);
	/* Free memory allocated for reading of input message from file */
	ossFreeMemory(world, encoded_data.value);
    }
    return err;
}

/*
 * Deserializes and prints input messages, creates and prints successful
 * outcome messages
 */
int main(int argc, char *argv[])
{
    OssGlobal world_data, *world = &world_data;
    int err = 0;

    err = ossinit(world, _oss_ngap_control_table);
    if (err)
	return reportError(NULL, "ossinit()", err, NULL);

    filesDir = argc > 1 ? argv[1] : ".";

    /* Set flags */
    ossSetFlags(world, AUTOMATIC_ENCDEC);
    /* Set debug mode */
    ossSetDebugFlags(world, PRINT_ERROR_MESSAGES | PRINT_DECODING_DETAILS | PRINT_ENCODING_DETAILS);
    err = testNGAP(world, "NGAP-PDU_HandoverRequest.per");
    /* Free all resources */
    ossterm(world);

    if (!err)
	printf("Testing successful.\n");

    return err;
}

Expected Output (Excerpt)

This is the expected output when running the sample:

Decoded NGAP message:
  ...
Encoding response message...
Encoding successful.

ASN.1 Schema Excerpt (ngap.asn)

Show excerpt from ngap.asn
-- Excerpt from ngap.asn 3GPP TS 38.413 V19.0.0 (2025-09) 

-- **************************************************************
--
-- Elementary Procedure definitions
--
-- **************************************************************

NGAP-PDU-Descriptions  { 
itu-t (0) identified-organization (4) etsi (0) mobileDomain (0) 
ngran-Access (22) modules (3) ngap (1) version1 (1) ngap-PDU-Descriptions (0)}

DEFINITIONS AUTOMATIC TAGS ::= 

BEGIN

-- **************************************************************
--
-- IE parameter types from other modules.
--
-- **************************************************************

IMPORTS

	Criticality,
	ProcedureCode
FROM NGAP-CommonDataTypes

	AMFConfigurationUpdate,
	AMFConfigurationUpdateAcknowledge,
	AMFConfigurationUpdateFailure,
	AMFCPRelocationIndication,
	AMFStatusIndication,
	BroadcastSessionModificationFailure,
	BroadcastSessionModificationRequest,
	BroadcastSessionModificationResponse,
	BroadcastSessionReleaseRequest,
	BroadcastSessionReleaseRequired,
	BroadcastSessionReleaseResponse,
	BroadcastSessionSetupFailure,
	BroadcastSessionSetupRequest,
	BroadcastSessionSetupResponse,
	BroadcastSessionTransportFailure,
	BroadcastSessionTransportRequest,
	BroadcastSessionTransportResponse,
	CellTrafficTrace,
	ConnectionEstablishmentIndication,
	DeactivateTrace,
	DistributionReleaseRequest,
	DistributionReleaseResponse,
	DistributionSetupFailure,
	DistributionSetupRequest,
	DistributionSetupResponse,
	DownlinkNASTransport,
	DownlinkNonUEAssociatedNRPPaTransport,
	DownlinkRANConfigurationTransfer,
	DownlinkRANEarlyStatusTransfer,
	DownlinkRANStatusTransfer,
	DownlinkUEAssociatedNRPPaTransport,
	ErrorIndication,
	HandoverCancel,
	HandoverCancelAcknowledge,
	HandoverCommand,
	HandoverFailure,
	HandoverNotify,
	HandoverPreparationFailure,
	HandoverRequest,
	HandoverRequestAcknowledge,
	HandoverRequired,
	HandoverSuccess,
	InitialContextSetupFailure,
	InitialContextSetupRequest,
	InitialContextSetupResponse,
	InitialUEMessage,
	LocationReport,
	LocationReportingControl,
	LocationReportingFailureIndication,
	MTCommunicationHandlingRequest,
	MTCommunicationHandlingResponse,
	MTCommunicationHandlingFailure,
	MulticastSessionActivationFailure,
	MulticastSessionActivationRequest,
	MulticastSessionActivationResponse,
	MulticastSessionDeactivationRequest,
	MulticastSessionDeactivationResponse,
	MulticastSessionUpdateFailure,
	MulticastSessionUpdateRequest,
	MulticastSessionUpdateResponse,
	MulticastGroupPaging,
	NASNonDeliveryIndication,
	NGReset,
	NGResetAcknowledge,
	NGRemovalFailure,
	NGRemovalRequest,
	NGRemovalResponse,
	NGSetupFailure,
	NGSetupRequest,
	NGSetupResponse,
	OverloadStart,
	OverloadStop,
	Paging,
	PathSwitchRequest,
	PathSwitchRequestAcknowledge,
	PathSwitchRequestFailure,	
	PDUSessionResourceModifyConfirm,
	PDUSessionResourceModifyIndication,
	PDUSessionResourceModifyRequest,
	PDUSessionResourceModifyResponse,
	PDUSessionResourceNotify,
	PDUSessionResourceReleaseCommand,
	PDUSessionResourceReleaseResponse,
	PDUSessionResourceSetupRequest,
	PDUSessionResourceSetupResponse,
	PrivateMessage,
	PWSCancelRequest,
	PWSCancelResponse,
	PWSFailureIndication,
	PWSRestartIndication,
	RANConfigurationUpdate,
	RANConfigurationUpdateAcknowledge,
	RANConfigurationUpdateFailure,
	RANCPRelocationIndication,
	RANPagingRequest,
	RerouteNASRequest,
	RetrieveUEInformation,
	RRCInactiveTransitionReport,
	SecondaryRATDataUsageReport,
	TimingSynchronisationStatusRequest,
	TimingSynchronisationStatusResponse,
	TimingSynchronisationStatusFailure,
	TimingSynchronisationStatusReport,
	TraceFailureIndication,
	TraceStart,
	UEContextModificationFailure,
	UEContextModificationRequest,
	UEContextModificationResponse,
	UEContextReleaseCommand,
	UEContextReleaseComplete,
	UEContextReleaseRequest,
	UEContextResumeRequest,
	UEContextResumeResponse,
	UEContextResumeFailure,
	UEContextSuspendRequest,
	UEContextSuspendResponse,
	UEContextSuspendFailure,
	UEInformationTransfer,
	UERadioCapabilityCheckRequest,
	UERadioCapabilityCheckResponse,
	UERadioCapabilityIDMappingRequest,
	UERadioCapabilityIDMappingResponse,
	UERadioCapabilityInfoIndication,
	UETNLABindingReleaseRequest,
	UplinkNASTransport,
	UplinkNonUEAssociatedNRPPaTransport,
	UplinkRANConfigurationTransfer,
	UplinkRANEarlyStatusTransfer,
	UplinkRANStatusTransfer,
	UplinkUEAssociatedNRPPaTransport,
	WriteReplaceWarningRequest,
	WriteReplaceWarningResponse,
	UplinkRIMInformationTransfer,
	DownlinkRIMInformationTransfer,
	InventoryRequest,
	InventoryResponse,
	InventoryFailure,
	InventoryReport,
	CommandRequest,
	CommandResponse,
	CommandFailure,
	AIOTSessionReleaseCommand,
	AIOTSessionReleaseComplete,
	AIOTSessionReleaseRequest


FROM NGAP-PDU-Contents

	id-AMFConfigurationUpdate,
	id-AMFCPRelocationIndication,
	id-AMFStatusIndication,
	id-BroadcastSessionModification,
	id-BroadcastSessionRelease,
	id-BroadcastSessionReleaseRequired,
	id-BroadcastSessionSetup,
	id-BroadcastSessionTransport,
	id-CellTrafficTrace,
	id-ConnectionEstablishmentIndication,
	id-DeactivateTrace,
	id-DistributionRelease,
	id-DistributionSetup,
	id-DownlinkNASTransport,
	id-DownlinkNonUEAssociatedNRPPaTransport,
	id-DownlinkRANConfigurationTransfer,
	id-DownlinkRANEarlyStatusTransfer,
	id-DownlinkRANStatusTransfer,
	id-DownlinkRIMInformationTransfer,
	id-DownlinkUEAssociatedNRPPaTransport,
	id-ErrorIndication,
	id-HandoverCancel,
	id-HandoverNotification,
	id-HandoverPreparation,
	id-HandoverResourceAllocation,
	id-HandoverSuccess,
	id-InitialContextSetup,
	id-InitialUEMessage,
	id-LocationReport,
	id-LocationReportingControl,
	id-LocationReportingFailureIndication,
	id-MTCommunicationHandling,
	id-MulticastGroupPaging,
	id-MulticastSessionActivation,
	id-MulticastSessionDeactivation,
	id-MulticastSessionUpdate,
	id-NASNonDeliveryIndication,
	id-NGReset,
	id-NGRemoval,
	id-NGSetup,
	id-OverloadStart,
	id-OverloadStop,
	id-Paging,
	id-PathSwitchRequest,
	id-PDUSessionResourceModify,
	id-PDUSessionResourceModifyIndication,
	id-PDUSessionResourceNotify,
	id-PDUSessionResourceRelease,
	id-PDUSessionResourceSetup,
	id-PrivateMessage,
	id-PWSCancel,
	id-PWSFailureIndication,
	id-PWSRestartIndication,
	id-RANConfigurationUpdate,
	id-RANCPRelocationIndication,
	id-RANPagingRequest,
	id-RerouteNASRequest,
	id-RetrieveUEInformation,
	id-RRCInactiveTransitionReport,
	id-SecondaryRATDataUsageReport,
	id-TimingSynchronisationStatus,
	id-TimingSynchronisationStatusReport,
	id-TraceFailureIndication,
	id-TraceStart,
	id-UEContextModification,
	id-UEContextRelease,
	id-UEContextReleaseRequest,
	id-UEContextResume,
	id-UEContextSuspend,
	id-UEInformationTransfer,
	id-UERadioCapabilityCheck,
	id-UERadioCapabilityIDMapping,
	id-UERadioCapabilityInfoIndication,
	id-UETNLABindingRelease,
	id-UplinkNASTransport,
	id-UplinkNonUEAssociatedNRPPaTransport,
	id-UplinkRANConfigurationTransfer,
	id-UplinkRANEarlyStatusTransfer,
	id-UplinkRANStatusTransfer,
	id-UplinkRIMInformationTransfer,
	id-UplinkUEAssociatedNRPPaTransport,
	id-WriteReplaceWarning,
	id-InventoryRequest,
	id-InventoryReport,
	id-CommandRequest,
	id-AIOTSessionRelease,
	id-AIOTSessionReleaseRequest


FROM NGAP-Constants;

-- **************************************************************
--
-- Interface Elementary Procedure Class
--
-- **************************************************************

NGAP-ELEMENTARY-PROCEDURE ::= CLASS {
	&InitiatingMessage				,
	&SuccessfulOutcome							OPTIONAL,
	&UnsuccessfulOutcome						OPTIONAL,
	&procedureCode				ProcedureCode	UNIQUE,
	&criticality				Criticality	DEFAULT ignore
}

WITH SYNTAX {
	INITIATING MESSAGE			&InitiatingMessage
	[SUCCESSFUL OUTCOME			&SuccessfulOutcome]
	[UNSUCCESSFUL OUTCOME		&UnsuccessfulOutcome]
	PROCEDURE CODE				&procedureCode
	[CRITICALITY				&criticality]
}

Using ASN.1 Studio (Optional)

The gui/ subdirectory contains an ASN.1 Studio project for this sample. With ASN.1 Studio you can:

  • Open the 5G NGAP ASN.1 modules.
  • Generate code from the ASN.1 schema.
  • Create and edit sample encoded 5G NGAP messages.
  • Export projects to gmake makefiles.

Related Samples

Disclaimer

This sample is provided solely for illustration purposes, for example to demonstrate usage of the OSS ASN.1 Tools API with 3GPP 5G NGAP messages. It does not represent a complete application. To build and run this sample, you must use a trial or licensed version of the appropriate OSS ASN.1 Tools. The copyright and license statements included in each source file remain fully applicable.

Need Help?

If you have questions about using this sample, contact OSS Nokalva Support.

See Also