Chapter 22 Voice over Internet Protocol (VoIP) – Linux Administration: A Beginner's Guide, Eighth Edition, 8th Edition



Voice over Internet Protocol (VoIP)

Since its introduction in 1995, Voice over IP, or simply VoIP, like Linux, has evolved rapidly, and it continues to revolutionize communication, replacing traditional telephone networks all around the world. Every day, more and more people communicate over VoIP. International and continental long-distance calls, local calls, and even calls via smartphone apps (applications on smartphones) utilize VoIP networks in ways most people never even think about.

In the following sections, we will review the fundamentals of VoIP technology and Internet telephony, describe the basic elements of VoIP, and show an implementation of VoIP using the open source framework created by the popular Asterisk project ( By the end of the chapter, you will have set up a fully functional VoIP system with which you can make and receive phone calls.

VoIP Overview

In its simplest form, VoIP is the transmission of digitized speech in “data packets” from one IP address to another over one or more IP networks, such as the Internet or a LAN. A VoIP system takes in uncompressed speech as an input, converts it into compressed digital form, packetizes it, puts it on the wire, and sends it to the next station, where the process is reversed, as shown in Figure 22-1. The accuracy and clarity of the reconstructed signal is dependent on various technical factors, such as the compression algorithms used, the encoding and decoding algorithms used, the sample rate, and so on. This is obviously an oversimplified version of how VoIP works.

Figure 22-1   Basic principles of VoIP

As with most complex systems, the VoIP system can be broken down into several individual components. A subset of the components we will be exploring in the following sections includes VoIP servers, analog telephone adapters, IP phones, and VoIP protocols.

VoIP Server

The VoIP server plays the role of the communications switch. It is central to all VoIP communications and is responsible for directing and controlling the VoIP communications among the various components. The VoIP server provides ways for end users to make and receive VoIP calls or interact with VoIP systems and other VoIP components.

Besides the seemingly all-important role of the VoIP server, it isn’t terribly useful by itself. Its needs and relies on the other components to realize its full potential.

Analog Telephone Adapter (ATA)

An ATA is a simple device that lets you connect any standard (analog) telephone to your network so it can use VoIP communication through your Internet connection. The ATA converts the analog signal from your telephone into digital data that can be transmitted over IP networks, such as your LAN or the Internet, and vice versa. VoIP providers, such as Vonage, Lingo, and magicJack, typically bundle an ATA device with their VoIP telephony service to make it easier for new customers to use their existing traditional analog phones with the VoIP service.

IP Phones

IP phones use VoIP technologies to transmit and receive telephone calls over the IP network. The IP phone converts your speech directly into digital signals and transmits it over the IP network, and vice versa. There are two common forms of IP phones:

•   Hardphone   A digital phone set that connects directly to an IP network without any other device.

•   Softphone   A software application that runs on a device such as your PC, smartphone, or tablet and relies on the underlying hardware to do the heavy lifting.

Figure 22-2 shows a simplified network layout of a VoIP setup using an ATA and IP phones.

Figure 22-2   VoIP network layout using an ATA and IP phones

VoIP Protocols

A typical VoIP connection generally involves a series of handshakes, also known as signaling, between the VoIP endpoints (and the components in between) to exchange information that culminates in two persistent media streams (one for each direction) that carry the actual conversation. Several protocols have been created to handle this exchange. We’ll discuss some of those that are important to VoIP in general and to Asterisk specifically.

For clarity, we categorize the VoIP protocols into three groups: signaling protocols, media protocols, and codecs.

Signaling Protocols

Generally, VoIP signaling controls the setting up, modifying, and tearing down of a conversation. The signaling protocols are not concerned with the nitty-gritty details of the data streams carrying the actual media content but rather focus on verifying the identities of the calling and called parties (authentication), ensuring that the network is not misused (authorization), and communicating the capabilities, such as call features and security, supported by the endpoints.

In rough chronological order of introduction, the most widely used signaling protocols for VoIP systems are detailed in Table 22-1.

Table 22-1   Signaling Protocols

Media Protocols

Media protocols are responsible for transporting multimedia data (such as audio and video) over IP networks. RTP and RTCP (RFC 3550) are closely linked media protocols that are often used for this purpose. Both are described in Table 22-2.

Table 22-2   Media Protocols


A codec (short for coder-decoder) is a set of instructions used to convert analog signals to digital form and then back again. The codec used is often referred to as the encoding method or the payload type for the RTP packet. Codecs differ in a number of ways, including sound quality, bandwidth, and computational requirements. Common codecs are described next:

•   G.711   Does not use compression and delivers precise speech transmission (toll quality). Mostly used over LAN or on high-bandwidth networks. Consists of two variants: μ-law, used in North America and Japan, and A-law, used in Europe and elsewhere.

•   G.722   A wideband codec that provides high sound quality and adapts well to varying compressions.

•   G.729A   Delivers good audio quality and provides excellent bandwidth utilization. It typically requires a license to use.

•   GSM   Similar to encoding used in GSM mobile phones. It provides high compression ratio and is free and available on many VoIP platforms.

•   Opus   An extension to the SILK codec developed by Skype. Supports constant and variable bitrate encoding and has good packet loss concealment (PLC).

•   iLBC   Internet Low Bitrate Codec. It is very resilient to packet loss and works well in low-bandwidth networks.

VoIP Implementations

A good number of VoIP systems are now implemented as services, and users typically only interact with the systems using endpoints such as a phone set, software application, or smartphone app to communicate with other users. The internal workings of these systems are complex and usually hidden from users.

VoIP systems can also be implemented to replace components of the traditional telephony infrastructure. Sample popular open source VoIP projects that provide Private Branch Exchange (PBX) functionality are FreeSWITCH, OpenSIPs, Asterisk, and FreePBX. We will focus on Asterisk because of its maturity and strong community base, which continually develops new features. Asterisk is also well documented with numerous online resources and individuals available to assist.


So what is Asterisk? Sponsored by Digium, Inc., Asterisk is their community software for building VoIP and PBX replacements. It is very flexible, runs on a variety of platforms, and supports numerous gateways, effectively turning an ordinary computer into an advanced communications server.

Asterisk software is used in IP PBX systems, VoIP gateways, conference servers, and other embedded applications. It includes high-end features such as interactive voice response (IVR), voicemail, conference calling, automatic call distribution (ACD), and so on. New functionalities can be created by writing scripts in Asterisk’s native language, Perl, or other languages, and by writing modules in C. Asterisk is capable of interfacing with many traditional telecom protocols, VoIP protocols, and a majority of the standard codecs. To sum it all up, Asterisk can be used to create powerful, programmable VoIP systems at relatively low cost compared to proprietary PBXs with similar features.

We will go over installing and configuring an Asterisk system and also discuss the structure of the main Asterisk configuration files.

How Asterisk Works

Asterisk consists of several software components and modules. This modularity provides the flexibility to build a customized Asterisk-based solution for your project. For example, the PJSIP module will allow your Asterisk system to communicate with SIP phone endpoints, while the Call Details Record (CDR) module will add call-reporting capabilities.

On a high level, Asterisk has a core that can interact with many modules. The modules, also called channel drivers, provide the channels that are driven by the Asterisk dialplan to execute programmed behavior and facilitate communication between devices or programs outside Asterisk. Channels often use bridging infrastructure to interact with other channels.

We will dig deeper into these concepts in later sections.

Asterisk Installation

Asterisk is complex. There are many steps to cover to install a fully functional system. The checklist in Table 22-3 provides the high-level steps in rough order required to install Asterisk.

Table 22-3   High-Level Steps to Install Asterisk

To keep things simple on our sample Fedora server, we’ll install the prepackaged Asterisk version 16 as well as the asterisk-pjsip package, which provides the PJSIP module. Without further ado, let’s get on with it!

1.   Start off by disabling SELinux:

2.   Verify that the Asterisk package exists in your distros’ online repository:

3.   Once this is verified, install the Asterisk packages that we’ll be using:

And that’s it—you now have Asterisk installed on your Fedora server!

Starting and Stopping Asterisk

In the following steps, we go over how to manage your Asterisk server after it has been successfully installed:

1.   On systemd-enabled distros, you can use systemctl to stop the Asterisk service:

2.   Use the systemctl command to enable the Asterisk service for automatic startup and simultaneously start it by running the following:

3.   Once you’ve verified that the service is running, you can connect to the Asterisk console:

Understanding Asterisk Configuration Files and Structure

The configuration files are the core of an Asterisk system. They give it character, purpose, and personality and differentiate one Asterisk implementation from another.

Table 22-4 lists the default installation paths for Asterisk component files and libraries. This is not an exhaustive list; only the core components relevant to this chapter are listed.

Table 22-4   Asterisk File Structure

To get started, we will focus on the specific files, and the options within those files, that are required to configure your first PBX.

TIP  Asterisk ships with sample configuration files that serve as very good reference to learn about other advanced options available in Asterisk configuration files.

The following are the configuration files you would interact with most of the time when configuring your Asterisk system:

•   pjsip.conf   Used to configure the PJSIP channels

•   extensions.conf   Used to configure the dialplan

•   modules.conf   Used to enable or disable the resources available to the Asterisk system

PJSIP Channel Config: pjsip.conf

The PJSIP channel config file, pjsip.conf, is a flat text file where we configure everything related to the SIP protocol; this includes adding new SIP users and defining SIP providers for both inbound and outbound calls. chan_pjsip is the new channel driver that replaces the older chan_sip driver, and thus, pjsip.conf replaces sip.conf. Unlike chan_sip, where everything is a channel, pjsip has a number of different conceptual objects.

pjsip.conf is composed of sections like most configuration files used with Asterisk. Each section defines the configuration for a configuration object within res_pjsip or an associated module. All section names are encased in square brackets, and anything that follows a section name is applied to that section. Each section will have a type option that defines what kind of section is being configured. You’ll see that in the following sample configuration sections.

Section Names   In general, you can name a section whatever makes sense to you. However, in some cases, specifically for the endpoint and/or types, the section name has a relationship to its function and must match the user portion of the SIP URI in the “From” header for inbound SIP requests.

Section Types   We will describe a few of the common sections you will use in your first Asterisk PBX. There are many config options for some of the sections, but the following examples are deliberately minimal for the sake of simplicity. For more details on the available options, visit

•   Transport   Configures the Transport layer options, like tcp, udp, and websockets, and the encryption methods, like TLS/SSL, the endpoint devices will use.

Here are the explanations for these settings:

•   AoR   Address of Record (AoR) specifies where an endpoint can be contacted. The contact object in the AoR can be configured dynamically, when a SIP endpoint is configured to register:

Or manually, when the endpoint is not configured for registration:

Here are the explanations for these settings:

•   Auth   This section holds inbound or outbound authentication options and credentials for use by endpoints, trunks, and registrations:

Here are the explanations for these settings:

•   Identify   Maps a host directly to an endpoint. If we do not define an Identify section, user identity is based on the packet’s SIP “From” header.

Here are the explanations for these settings:

•   Endpoint   Specifies core SIP functionalities and their relationships to other sections, such as Auth, AoR, and Transport. This essentially describes the configuration of a SIP endpoint or a remote service, such as a phone or SIP Trunk service.

Here are the explanations for these settings:

TIP  If your endpoints are behind a NAT router or firewall, relative to the Asterisk server, then you can add the following NAT configurations to your endpoint configurations:

direct_media=no   Species whether media may flow directly between endpoints. Set to no to ensure Asterisk is in the media path.

rtp_symmetric=yes   Set to yes to enforce that RTP must be symmetric.

force_rport=yes   Configuration to force use of return port. Default is yes.

•   Registration   Configures outbound connection with another system, such as an Internet telephony service provider (ITSP). This connection is often referred to as SIP trunking.

Here are the explanations for these settings:

You can review the configurations of the pjsip objects by connecting to your Asterisk console and typing the following:

For example, here we review the configuration of the AoR object:

Now that the SIP entities are defined, the next section introduces how to configure the actions that Asterisk will perform when interacting with these entities and channels.

The Dialplan: extensions.conf

At the heart of every PBX is its dialplan: the logic that determines which connections are made based on the number and pattern of the digits dialed for all incoming and outgoing calls. The dialplan is a scripting language specific to Asterisk and is one of the primary ways of instructing Asterisk to route and manipulate calls in a programmatic way.

The dialplan is configured in /etc/asterisk/extensions.conf and is organized in sections. The sections are used for static settings and definitions, as well as for executable dialplan components, and are referred to as contexts. The contexts are used to manage all assigned telephone numbers within the Asterisk system, and almost all functionalities of the Asterisk system are defined in the contexts, such as IVR menus, call forwarding, and hunt groups. Access and capabilities that are available to the clients and users are also defined within contexts, such as defining a group of phones that might be able to make outgoing calls and restricting another group to only internal calls. In general, a dialplan looks like this:

Here are the explanations for these settings:

Modules: modules.conf

Asterisk is built on modules. A module is a loadable component that provides a specific functionality, such as a channel driver, resource, codecs, or applications. The modules.conf file is the Asterisk Module Loader configuration file, where all of the modules to load or not to load from the modules directory (/usr/lib64/asterisk/modules/) at startup of Asterisk are configured.

As an analogy, all of these modules make up the organs and limbs of the Asterisk system. Though the modules.conf file is not strictly required for an Asterisk setup, the Asterisk system cannot provide any functionality without the modules.

Type the command module show to review the modules that are loaded in your Asterisk system. Note that your console output will probably be different from the following list.

For our first PBX installation, we will accept the default configuration directives in the modules.conf file. Let’s review our sample module.conf file to understand the inner workings of the module loading subsystem.

To view the modules.conf file, enter the following:

You will see the [modules] section is the only section in the modules.conf file. Table 22-5 summarizes the options available.

Table 22-5   Modules.conf [modules] Section

NOTE  With the exception of autoload, all the options in Table 22-5 may be specified more than once.

TIP  Asterisk can be fussy about its modules. To avoid the wrath of this fussiness, it’s best for newcomers to Asterisk to err on the side of being overly generous by setting autoload=yes. As you get more familiar with Asterisk, you can use the noload directive to explicitly instruct Asterisk not to load unneeded modules.

Asterisk Network, Port, and Firewall Requirements

VoIP relies on your network being optimized for connectivity and good sound quality. Most of the sound quality issues that you will experience with the Asterisk system will be network related. If it is at all possible, all VoIP-related traffic on the network should be segmented away from other day-to-day network traffic. This can be done through the use of a virtual local area network (VLAN) and/or through the use of dedicated networking equipment. All relevant network infrastructure equipment should be optimized to prioritize VoIP traffic.

This section assumes that your Linux server has some default firewall rules in place to protect the system. To proceed with the Asterisk setup and to make sure the relevant asterisk components are reachable on the network, we need to ensure that the firewall subsystem on the server allows access to the necessary ports required by Asterisk.

Table 22-6 summarizes some default ports required by Asterisk. If needed, the ports can be changed in the various configuration files specific to the protocols and applications.

Table 22-6   List of Common VoIP Protocol Port Numbers

Configuring the Local Firewall for Asterisk

For the exercise, we will configure the firewall to allow traffic on port 5060 for SIP signaling and ports 10000 through 20000 for the RTP (media) traffic. You can also narrow the range of RTP ports in the /etc/asterisk/rtp.conf file.

On Red Hat–like distros such as Fedora, Centos, or RHEL, use the firewall-cmd command to open the required ports (5060 and 10000–20000) by running the following:

For Debian-based systems such as Ubuntu, you can use UFW (Uncomplicated Firewall). Type the following commands:

Be aware that the preceding commands will allow all UDP traffic from any (possibly untrusted) source address to access port 5060 and the entire port range 10000 through 20000 on your server! On a production server, you will want to be stricter and more deliberate when crafting your firewall rules.

Configuring the PBX

Now that you have a fully installed Asterisk server and verified that it is running, you will proceed to configure your first PBX. There are a number of technologies supported by Asterisk to configure both the local extensions and the connection to the outside world, such as SIP, XMPP, IAX2, and so on.

In this chapter we will focus on connectivity using the SIP protocol. Configuring a SIP phone to work with Asterisk is not complex. However, because there are so many options possible in both Asterisk and the configuration of the particular telephone set or softphone, things can get confusing. What we are going to do, therefore, is give you the bare-bones basics. At the end of this chapter, you will be able to configure the VoIP phone selected for the exercises (and be equipped with enough background knowledge to configure most SIP phones available today). We are not claiming that this is the best way, or only way, but we hope it will form a foundation from which to take a basic configuration and tweak things until you get the solution you need.

NOTE  We did not use any GUI implementation in this chapter because we want to expose you to the nuts and bolts of the Asterisk project. You may decide to pick any GUI of your choice afterward. However, in production environments, using a GUI is discouraged on Asterisk servers because it is a waste of resources and can hamper performance of your VoIP platform.

We’ll build up our PBX to a very simple configuration consisting of only two SIP phones and a connection to the public switched telephone network (PSTN) to make phone calls to regular mobile phones and landlines, as shown in Figure 22-3. This minimal configuration should provide a good foundation to demonstrate how incoming and outgoing calls are routed through the dialplan.

The configuration in Figure 22-3 consists of the following items:

Figure 22-3   Your first VoIP PBX configuration

•   One Asterisk server

•   Two SIP extensions: Alice, at extension 1001, and Bob, at extension 1002

•   One outside connection through an ITSP, Twilio, using its Elastic SIP Trunk

•   One local phone number from the ITSP to receive calls from the PSTN (for example, with caller ID 1-408-555-1212)

TIP  We’ve bundled working copies of the configuration and/or script files used in this chapter at the following URL to save you some typing:

The files are named descriptively to match the scenario. If you choose to follow along using this bundle, just download the archive, extract its contents (decompress it), and then rename and copy the file(s) to the proper directories on your local system.

Local Extensions

The term local extensions refers to telephone sets, or endpoints, attached to the Asterisk server. Typical configurations enable the local extensions to communicate with each other at a reduced cost (usually free) and also allow calls out to the PSTN, if the Asterisk server has external connection to the PSTN.

We will set up the local extensions in the following sections. The entire configuration and setup process involves configuring SIP extensions on the server in the pjsip.conf file, configuring the dialplan on the server in the extensions.conf file, downloading and installing a softphone (SIP/VoIP client), and configuring the softphone for the local extensions. Finally, we’ll run through a test scenario where we dial from one extension to another.

PJSIP Channel Configuration (pjsip.conf)

Let’s back up the original pjsip.conf config file to pjsip.conf.original:

Use your favorite text editor to create a new /etc/asterisk/pjsip.conf with the following configuration. We use the nano editor in this example:

Save your changes to the file and quit the editor when you are done.

This configuration will enable extensions 1001 and 1002 and make them available for the SIP devices. auth= is used for the endpoint as opposed to outbound_auth= since we want to allow inbound registration for this endpoint. max_contacts= is set to something nonzero, as we want to allow contacts to be created through registration.

We used callerid= to set the caller ID information for the endpoint. Caller ID is in the format Name <Number>, or only <Number>.

The contact option (IP address and port) in the aor section will be configured dynamically from the registration information of the SIP endpoint.

Connect to the Asterisk console and reload the PJSIP configuration:

TIP  You can execute Asterisk commands without always first having to connect to the native Asterisk console. To do this, use the -rx option followed by the sub-command that you want to execute. For example, here is the full command to run the "pjsip reload" sub-command:

And similarly, to show the current dialplan, you would run the following:

Now list the available SIP endpoints and you will see the two SIP phones we just configured in the pjsip.conf file in the console output. You will notice that State is Unavailable to indicate that the device is offline, and no endpoint is registered.

Dialplan Configuration (extensions.conf)

The sample dialplan that ships with the Asterisk package contains many interesting parameters/settings in its default and unmodified state, but since these are not needed for this exercise, we’ll rename/back up the original file and create a new one from scratch:

Then use a text editor to create a new extensions.conf file with the following contents:

Save your changes and exit the text editor.

Connect to the Asterisk console and reload the configuration:

Congratulations! You have set up and configured an Asterisk system that is capable of allowing phone conversations between two SIP devices. This simple setup is not dependent on any other external services or infrastructure beyond your private network or LAN.

However, there is one more component missing—the telephones!

Configure the Phone Sets (Softphone) for the Local Extensions

The Asterisk system works with many different types of phone endpoints, which can be either IP phones or analog phones attached to an ATA. All of these phone types have the same basic SIP configuration, and once you understand the fundamental concept of SIP configurations, you will be able to configure almost any phone set.

A principle to follow is to start your configurations in the simplest manner possible, as we have done in previous sections, and leave the Asterisk configuration static. Then move on to configure the phone sets and carry out tests. If you have followed the steps up to this point in the chapter, you should have a working system configured and now can focus on getting your phone sets to work so that you can make and receive calls. You will be in a far better position to begin experimenting with different settings. We have seen too much suffering (including ours!) that stems from overly complicated configurations, and we want it to end here and now!

You will need at least two phone endpoints to configure the extensions and to make and receive calls. For simplicity, we will use the free X-Lite softphone from CounterPath, Inc., for each of the extensions and install it on two different computers, smartphones, or tablets.

TIP  In the configuration menus of the phone itself, you will want to look for fields that are labeled user name, auth name, authentication name, and so on. The thing to remember is that since you know that the Asterisk end of the equation is configured simply and correctly, you can experiment with the phone settings until you find a combination that works.

Download and Install the X-Lite Softphone

Follow these steps to obtain and configure the X-Lite softphones on each of the client systems or devices from which you want to run the SIP clients:

1.   Launch your favorite browser and go to

2.   Click the Download button for the operating system of the computer on which you want to install the softphone.

3.   Follow the instructions to install the software and then launch the X-Lite software.

4.   Repeat Steps 1–4 on the second system that will be running the X-Lite software and acting as the second extension.

Configure the SIP Extensions

After installing the SIP clients as described, you’ll need to configure the SIP extensions as follows:

1.   Set up your SIP accounts. Go to Preferences → Account Settings.

2.   Fill out the screen, shown next, with the following values:

User ID: 1001
Domain: <>
Password: herSecret
Display name: Alice

3.   Click OK to save the configuration and attempt to connect to the Asterisk server.

4.   Repeat Steps 1–3 to configure the second X-Lite SIP client (Bob). Substitute all the information for Alice (User ID:1001, Password: herSecret. Display name: Alice) with Bob’s correct information wherever applicable (User ID: 1002, Password: hisSecret, Display name: Bob).

Before we continue to the next section, you can run the following commands on the Asterisk console to verify the configuration of the softphone and ensure that they both are registered correctly:

The X-Lite client will show the presence status as Available, as shown here:

NOTE  The status information may look different on your version of softphones (and hardphones).

Test Scenario: Dial from Alice (Extension 1001) to Bob (Extension 1002), First Phone Call

The reward for your hard work is to hear the first phone ring. So, let the fun begin!

For this scenario, we’ll call Bob’s extension from Alice’s extension:

1.   Launch both softphones, ensure that they are both registered to the Asterisk server, and check that the status is set to Available.

2.   On Alice’s softphone (1001), enter 1002 on the keypad.

3.   You should hear and observe Bob’s phone ringing and showing the caller ID of Alice as the caller, as shown next:

4.   Ensure you are able to speak into one of the phones and get good audio from the other phone, and vice versa.

5.   Hang up. Then make a few more test calls.

Outside Connection (VoIP Trunking)

Outside connection is the ability to be able to communicate with devices outside of your private network or LAN. This capability, generally known as VoIP trunking, extends the practical uses of the server, because it not only allows users to make calls to others outside of the private local network, but it also allows your internal users to be reachable from outside. Asterisk supports a number of different technologies to interconnect to outside networks, and these fall into two main categories (described next) depending on whether the interconnectivity is digital or analog:

•   Connectivity using a VoIP gateway   If you own a PSTN line (regular telephone line provided by your local telecom provider, also known as plain old telephone service, or POTS), you can connect it to your Asterisk server to make and receive calls. Similar to the ATA, you will need a device to connect your analog PSTN line to your Asterisk system. This device is called a VoIP gateway or PSTN gateway; and works as a bridge between the VoIP network and the PSTN. Depending on where the voice traffic originates from, the VoIP gateway will convert the voice traffic into the proper form for receipt by the destination network (IP or PSTN). The VoIP gateway may be a stand-alone device connected to your LAN, such as the Cisco SPA122, or a PCI card installed in your Linux server from a manufacturer such as Digium, Sangoma, AudioCodes, or Obihai.

•   Connectivity through an Internet telephony service provider (ITSP)   It is still possible to connect to outside networks even if you do not own a traditional PSTN line. This is achieved by interconnecting to one of an increasing number of ITSPs. Asterisk supports various protocols for interconnection, including SIP and XMPP. ITSPs provide various services, including, but not limited to, outbound calling, inbound calling, or both. Your choice of ITSP will ultimately depend on the services you require, your budget, and the call quality offered by the ITSP. Most ITSPs will provide sample Asterisk configuration to help get you connected to their service as quickly as possible.

In the next section, we will walk you through a common setup that will help you get started with SIP technology. The configuration may differ slightly depending on which ITSP you use and its specific implementation.

Regardless of the method you use to achieve outside connectivity, Asterisk treats these methods as channels, much like the PJSIP channels we set up earlier, and controls them through the dialplan.

Trunking Using Twilio Elastic SIP Trunks

Twilio Elastic SIP Trunks provide flexible, enterprise-ready, global connectivity for your VoIP infrastructure. Through the Twilio console, you can sign up and purchase phone numbers, referred to as Direct Inward Dialing numbers, or simply DIDs, from different area codes within the U.S., as well as DIDs from most other countries, and configure them to route calls to and from your Asterisk system.

Configuring Twilio Elastic SIP Trunks

Let’s walk through the steps needed to configure SIP Trunks using Twilio:

1.   To get started, you will need a new or existing Twilio account. See the Twilio SIP Trunking site for more details (

2.   Once you have signed up, log into the Twilio Console (

3.   Click the “All Products and Services” icon (…) and then click the Elastic SIP Trunking icon.

4.   From the Elastic SIP Trunking Dashboard screen, click the Get Started button or select the Getting Started menu/link.

5.   Click the Create a SIP Trunk button to create a new SIP Trunk.

NOTE  You can also create the SIP Trunk by selecting the Trunks menu item and clicking the Create New SIP Trunk button.

6.   Add a friendly name to identify this trunk and then click the Create button.

At this point, we’ve created the shell of the trunk. Let’s now configure the trunk.

Trunk Configuration

The Twilio SIP Trunk supports incoming and outgoing calls between your Asterisk server and the PSTN. Settings for outgoing calls will be configured under Termination, and incoming calls via your Twilio provisioned numbers will be configured under Origination. You’ll also need to associate Twilio numbers with your trunk under the “Numbers” page. We’ll see these next.


1.   From the menu on the left, under the Elastic SIP Trunking section, select Termination.

2.   In the Termination SIP URI field, enter a unique URI. The interface would verify and notify you if your selected URI is available. For our exercise, we entered ch22voip so that our Termination SIP URI becomes

3.   Select and configure at least one authentication scheme to use to authenticate your Asterisk server to Twilio—either IP ACL or Credentials List, or both. The IP ACL restricts termination of calls to the IP addresses specified. Credentials List provides a username and password to authenticate your requests to the Termination URI.

In IP access Control Lists, click the + button to create a new access control list.

Properties FRIENDLY NAME: <example: MyPBXACL>
IP ADDRESS: <your_server_NAT_public_IP_Address>
IP Address FRIENDLY NAME: <example: MyFedoraAsteriskServer>

4.   Click the Create ACL button.

NOTE  In the future, you may have other Asterisk PBXs you want to allow to communicate with your SIP termination URI. Simply add their public or NAT IP addresses and a corresponding friendly name to the IP ACL.

5.   Click the + button to create Credential Lists. Enter a friendly name. Select a unique username and strong password (minimum length of 12 characters, at least one number, uppercase character, and lowercase character). Configure the following fields:

FRIENDLY NAME: <your_friendly_name>
USERNAME: <your_unique_username>
PASSWORD: <your_credential_password>

6.   Click the Create button when finished.

NOTE  You can create multiple credentials to authenticate with your Termination SIP URI. The username and password credentials will be used in the auth section in the pjsip.conf configuration file of the Asterisk server.

7.   Scroll down to the bottom and click Save. You should receive confirmation you have successfully updated your SIP Trunk.


1.   From the menu on the left, under the Elastic SIP Trunking section, select Origination.

2.   Click Add New Origination URI to create a new Origination URI that defines the entry point URI (or public or NAT IP address; for example, to your Asterisk PBX. Also, set the Priority and Weight options to 10.

3.   Check the ENABLED box and then click the Add button.

Assign Telephone Number to the Elastic SIP Trunk

At this stage, we have completed the internal Twilio configuration; the next step is to configure and assign the telephone number that will be called to reach your Asterisk PBX.

You have the option to purchase a new number from Twilio, to assign an existing Twilio number, or to “port” a number you own on another network to Twilio and assign that number to your trunk, or any combination of these three options. For this exercise, we will buy a new number.

CAUTION  Purchasing a number from Twilio is not free. At time of writing, each number costs $1 per month. If you purchase a number, you may cancel it at any time to stop payment by releasing the number in the Number menu option.

1.   From the menu on the left, click Numbers.

2.   Click on the Buy a Number button.

3.   Search for a number that meets your criteria. You can search based on a specific number or parts of a number, by location, or by capabilities.

4.   Click the Buy button next to the number you select.

5.   Then click Buy This Number to confirm your purchase of the number.

Your purchased number should now be associated with your SIP Trunk.

IP Address Whitelist

In the next steps, we will configure your network infrastructure to ensure that Twilio has connectivity to your Asterisk PBX and vice versa.

1.   Click <Back to go back to the Elastic SIP Trunking menu, and then select Networking Info.

2.   Scroll down to the IP Address Whitelist section and note the Twilio IP addresses and port ranges in the region(s) that you have phone numbers.

3.   Whitelist these in your environment at your firewalls and/or ACLs. These IP addresses are the gateways that calls will originate from for those numbers.

4.   Since we elected to authenticate by IP address, in addition to the credentials, we must also configure the signaling IPs in the Twilio identify section in the pjsip.conf file.

This completes the Twilio-specific configuration. We will integrate your Twilio number service to your Asterisk server in the next sections.

SIP Trunk Configuration (pjsip.conf)   The Twilio Elastic SIP Trunk, as the name indicates, utilizes the SIP protocol for signaling. We will add the trunk configurations to the pjsip.conf file. Similar to the configurations of the internal extensions, we will configure the auth, aor, endpoint, and identify sections for the Twilio trunks.

1.   We’ll start by taking a backup of the working internal extensions configuration so we can roll back to our last known working configuration if we run into issues:

2.   Edit the pjsip.conf file and add the following contents:

3.   Configure the Twilio credentials in the auth section by adding the following:

The username and password are the credentials created in the Credentials Lists in the Twilio console.

4.   Configure the Termination SIP URI you configured in the Twilio console in the contact field of the Address of Records (aor) section:

The contact field is the Twilio target that outgoing calls (SIP INVITEs) will be sent to. In our example, we configured The qualify_frequency is the interval at which SIP NOTIFY messages will periodically be sent to the Twilio server to determine both its availability and the latency of its replies.

5.   Specify the signaling IPs in Step 4 in the IP Address Whitelist section to allow Asterisk to recognize the endpoint when a call comes in:

TIP  For North American gateways, you can also configure the match fields as follows:

match =

match =

6.   Configure the characteristics of the Twilio endpoint in the endpoint section:

7.   Enable the trunk configuration by reloading the pjsip module in the Asterisk console:

8.   While still at the Asterisk console, review the configuration:

Dialplan Configuration: Incoming Calls (extensions.conf)   Now that you have configured your Twilio account, obtained an inbound U.S. number from Twilio (say, 408-555-1212), and have successfully configured your connection to the Twilio server, the Twilio Elastic SIP Trunks service will forward any calls to your Twilio number to your Asterisk system using the configured Termination SIP URI. The next step is to describe how your Asterisk system will handle the call when it is received in the dialplan.

Let’s configure the dialplan to receive an incoming call from Twilio and route it to Alice, at the SIP phone you created with extension 1001.

Edit your dialplan and insert the following at the end of the file:

The exten => _+1NXXNXXXXXX matches a full E.164-formatted U.S. number. Once the call is received, Asterisk dials extension 1001 and then bridges the call when answered by Alice.

TIP  If you have numbers from other regions, outside North America, adjust this match criteria accordingly. For regions that have numbers with variable lengths, you can also create a match pattern using the “.” wildcard, as follows:

exten => _+44X.

This pattern will match any number that starts with +44[0-9]….

Dialplan Configuration: Outgoing Calls to PSTN (extensions.conf)   The Twilio network requires dialed numbers to be in E.164 format.

Edit your dialplan and insert the following at the end of the /etc/asterisk/extensions.conf file under the [outgoing] section:

If you want to support the North American Numbering Plan (NANP), which allows 7- and 10-digit dialing, in addition to the 11-digit dialing, then add the following to the [outgoing] context to match 7- and 10-digit numbers and append +1 to the Dial() application:

And in the same vein, add the following configuration to also support 7-digit dialed numbers. Append +1<your_area_code> to the Dial() application. In this example, the area code is 408:

Finally, we need to allow the internal phones to use the twilio trunk to make outgoing calls. Enable this by adding the following to the [internal] context:

Save all the changes to the files you edited and reload all the configurations, like so:

Test Scenario: Dial from a Phone Extension to the PSTN

Now make a call from either Alice’s or Bob’s softphone to the PSTN:

1.   Launch Alice’s (or Bob’s) softphone.

2.   Dial a PSTN routable number—you can dial your mobile or home phone number.

3.   You will hear a ringback tone coming from the softphone and the dialed number will start ringing. If the ITSP supports custom caller ID, the caller ID displayed on the dialed number will be the caller ID you set with the CALLERID(all)= option. Otherwise, the caller ID will be the DID you configured into the system.

4.   Ensure you are able to speak into one of the phones and get good audio from the other phone, and vice versa.

5.   Hang up. Then make a few more test calls.

Test Scenario: Inbound Call from the PSTN

The final scenario is to call the DID from a PSTN number to ring to the configured extension:

1.   Launch Alice’s (or Bob’s) softphone.

2.   Dial the assigned DID from a mobile phone or landline:

3.   You will hear a ringback tone coming from your mobile phone, and Alice’s softphone will start ringing and display the caller ID of the caller.

4.   Answer Alice’s extension and ensure you are able to speak into one of the phones and get good audio from the other phone, and vice versa.

5.   Hang up. Then make a few more test calls.

Asterisk Maintenance and Troubleshooting

Every effort has been made to ensure you do not experience any issues with the preceding examples, but, hey, stuff happens, interfaces change, and modules are deprecated every day. In real-world scenarios, you may run into issues originating from the network, host server, Asterisk configurations, or even issues and service outages from the VoIP provider! This section introduces some commands and tips to help you troubleshoot common problems.

Asterisk CLI Commands

Asterisk CLI commands follow this general syntax:

For example:

•   pjsip list endpoints   Returns a list PJSIP endpoints

•   core set verbose xx   Sets level of verbose chattiness

Helpful CLI Commands

To list the CLI commands available in the Asterisk console, simply type the following:


Both will list valid CLI commands available on your server.

The following shows help on a specific command:

TIP  The Asterisk CLI supports command-line completion on all commands, including many arguments. To use it, simply press the TAB key at any time while entering the beginning of any command. If Asterisk can complete the command unambiguously, it will do so; otherwise, it will complete as much of the command as possible. Additionally, Asterisk will print a list of all possible matches.

Next are some often-used commands for managing and troubleshooting Asterisk:

•   core restart now   Immediately restarts Asterisk. You will exit the CLI and be returned to the Linux prompt.

•   core stop now   Immediately stops Asterisk and drops back to the Linux prompt.

•   core show calls [uptime]   Displays information on calls.

•   core show channels [concise|verbose|count]   Displays calls information on channels.

•   core show channel   Displays calls information on a specific channel.

•   dialplan show   Displays all of the active (in-memory) dialplan. This includes, but is not limited to, the configuration contained in /etc/asterisk/extensions.conf.

•   channel request hangup   Requests a hangup on a given channel.

•   channel request hangup all   Requests a hangup on all active channels.

•   core reload   Globally reloads the configuration files.

•   dialplan reload   Reloads extensions and only extensions.

•   pjsip reload   Reloads SIP configuration.

•   pjsip show channel   Shows detailed PJSIP channel info.

•   pjsip show endpoints   Shows PJSIP endpoints.

•   pjsip show contacts   Shows PJSIP contacts.

Common Issues with VoIP

We’ve equipped you with the basics of setting up and configuring a simple VoIP server in this chapter. However, many things can still go wrong or prevent you and your users from getting the best VoIP experience possible. Even more annoying is that some of the factors causing this are usually out of your control and hard to pinpoint.

After all of your (and our) best efforts, you may find that the issues are simply because the planets are not properly aligned. Needless to say, this chapter can’t help in cases where Neptune is not properly aligned with Saturn, but you can at least equip yourself with the knowledge about some of the technical issues (Quality of Service, latency, jitter, and so on) discussed next.

Quality of Service

It should be noted that no matter how well tuned you think your network is, and no matter how good the statistics say your calls are, it is the subjective perception of call quality that is important to the end user. Quality of Service, or QoS, refers to the perceived quality of a call and the overall performance of a VoIP network.

To quantitatively measure QoS, several related aspects of the network service are often considered, such as packet error rates, bandwidth, throughput, transmission delay, availability, jitter, and so forth.


Latency is the delay in the delivery of data packets across a network. As a rule of thumb, a normal flow of conversation is possible if you can deliver the sound produced by the speaker to the listener’s ear within 150 milliseconds. Packet delays exceeding 250 milliseconds make normal conversation increasingly awkward and frustrating, and usually causes the communicating parties to start to talk on top of each other. Beyond 500 milliseconds, the communication becomes unintelligible.

Packet Loss

In addition to getting digitized voice packets to the destination on time, it is essential to ensure that the transmitted information arrives intact. If packet loss occurs in a network, the receiving endpoint will not be able to completely reproduce the sampled audio, which results in gaps in the data and is heard as static or, in severe cases, results in entire missed words or sentences. Packet loss of as low as 1 percent can severely impede VoIP calls using a G.711 codec. Ideally, there should not be any packet loss on the network.


Jitter is defined as a variation in the delay of received packets. It is used to indicate when data packets arrive either ahead of or behind a standard clock cycle due to network congestion, improper queuing, or configuration errors. If jitter is too large in a data stream, some packets are discarded and the receiving endpoint may hear dropouts in the audio.

Some devices are QoS aware and can compensate for the jitter that is encountered by introducing a jitter buffer. The jitter buffer stores these packets and then plays them out in a steady stream to the digital signal processors (DSPs), which can then convert them back to an analog audio stream.

Out-of-Order Delivery

Data packets routed through a network may take different routes, each resulting in a different delay. As a result, the packets may arrive in a different order from the order in which they were sent. The out-of-order packets will result in garbled audio. To correct this condition, there are special network protocols responsible for rearranging out-of-order packets before delivery to the receiving device. The extra processing done by this rearranging can introduce latency into the network.


Granted, SELinux is not specifically a VoIP issue, nor is it even a bad thing—when it is configured properly. However, when starting out with Asterisk on distros that implement SELinux and whenever things are not working as expected, we recommend disabling SELinux.


This chapter discussed the fundamentals of Voice over Internet Protocol (VoIP) and described some of the most common types of VoIP implementations, which include the use of analog telephone adapters (ATAs) and IP phones to directly connect to a VoIP service.

We discussed a few different types of VoIP implementations and used the open source Asterisk software to describe an implementation of VoIP. The exercises in the chapter were designed to walk you through basic configurations of the Asterisk system, showing you the steps necessary to set up a fully functional VoIP system that enables you to make calls between two endpoints and communicate with phone numbers in the public network (PSTN).

There is a lot more that can be discussed about the subject of VoIP and Asterisk than we can fit in one chapter; however, we hope we’ve armed you with the basic knowledge and skills required to be creative and expand upon to build more advanced features and capabilities.

You are now fully positioned to set up your VoIP server to compete with major providers such as AT&T, Bell Canada, Vodafone, MTN, Orange, Deutsche Telekom, Telstra, Verizon, Telefónica, Vonage, Lingo, magicJack, and so on!