Core Cookbook

Version: Kamailio SIP Server v5.8.x (devel)


This tutorial collects the functions and parameters exported by Kamailio core to configuration file.

Note: The parameters on this page are NOT in alphabetical order.


The structure of the kamailio.cfg can be seen as three parts:

  • global parameters
  • modules settings
  • routing blocks

For clarity and making it easy to maintain, it is recommended to keep them in this order, although some of them can be mixed.

Global Parameters Section

This is the first part of the configuration file, containing the parameters for the core of kamailio and custom global parameters.

Typically this is formed by directives of the form:


The name corresponds to a core parameter as listed in one of the next sections of this document. If a name is not matching a core parameter, then Kamailio will not start, rising an error during startup.

The value is typically an integer, boolean or a string.

Several parameters can get a complex value which is formed from a group of integer, strings or identifiers. For example, such parameter is listen, which can be assigned a value like proto:ipaddress:port.

Example of content:






Usually setting a parameter is ended by end of line, but it can be also ended with ; (semicolon). This should be used when the grammar of a parameter allows values on multiple lines (like listen or alias) and the next line creates a conflict by being swallowed as part of value for previous parameter.


If you want to use a reserved config keyword as part of a parameter, you need to enclose it in quotes. See the example below for the keyword "dns".

listen=tcp: advertise "":5060

Modules Settings Section

This is the second section of the configuration file, containing the directives to load modules and set their parameters.

It contains the directives loadmodule and modparam. In the default configuration file starts with the line setting the path to modules (the assignment to mpath core parameter.

Example of content:

loadmodule ""
modparam("debugger", "cfgtrace", 1)

Routing Blocks Section

This is the last section of the configuration file, typically the biggest one, containing the routing blocks with the routing logic for SIP traffic handled by Kamailio.

The only mandatory routing block is request_route, which contains the actions for deciding the routing for SIP requests.

See the chapter Routing Blocks in this document for more details about what types of routing blocks can be used in the configuration file and their role in routing SIP traffic and Kamailio behaviour.

Example of content:

request_route {

    # per request initial checks


branch_route[MANAGE_BRANCH] {
    xdbg("new branch [$T_branch_idx] to $ru\n");

Generic Elements


Line comments start with # (hash/pound character - like in shell) or // (double forward slash - like in C++/Java).

Block comments start with /* (forward slash and asterisk) and are ended by */ (asterisk and forward slash) (like in C, C++, Java).


      # this is a line comment

      // this is another line comment

      /* this
         comment */

Important: be aware of preprocessor directives that start with #! (hash/pound and exclamation) - those are no longer line comments.


There are three types of values used for parameters, assignments, arithmetic or string expressions:

  • integer - numbers of 32bit size
  • boolean - aliases to 1 (true, on, yes) or 0 (false, off, no)
  • string - tokens enclosed in between double or single quotes


// next two are strings

  "this is a string value"
  'this is another string value'

// next is a boolean


// next is an integer


Note: be aware of specific rules for logical evaluation of expressions and return codes, see the docs for IF and return.


Identifiers are tokens which are not enclosed in single or double quotes and to match the rules for integer or boolean values.

For example, the identifiers are the core parameters and functions, module functions, core keywords and statements.




The variables start with $ (dollar character).

You can see the list with available variables in the Pseudo-Variables Cookbook.


$var(x) = $rU + "@" + $fd;


An action is an element used inside routing blocks ended by ; (semicolon). It can be an execution of a function from core or a module, a conditional or loop statement, an assignment expression.


  sl_send_reply("404", "Not found");


An expression is an association group of statements, variables, functions and operators.




"sip:" + $var(prefix) + $rU + "@" + $rd

Config Pre-Processor Directives

Pre-processor directives are evaluated before building the execution tree (before 'understanding' configuration file content). They require an end-of-line (\n) after each one in order to be properly identified (e.g., #!else\n, #!endif\n).


    include_file "path_to_file"

Include the content of the file in config before parsing. path_to_file must be a static string. Including file operation is done at startup. If you change the content of included file, you have to restart the SIP server to become effective.

The path_to_file can be relative or absolute. If it is not absolute path, first attempt is to locate it relative to current directory, and if fails, relative to directory of the file that includes it. There is no restriction where include can be used or what can contain - any part of config file is ok. There is a limit of maximum 10 includes in depth, otherwise you can use as many includes as you want. Reporting of the cfg file syntax errors prints now the file name for easier troubleshooting.

If the included file is not found, the config file parser throws error. You can find this error message at the logging destination, usually in the system logging (file).

You can use also the syntax #!include_file or !!include_file.

Example of usage:

request_route {
    include_file "/etc/kamailio/checks.cfg"
  • /etc/kamailio/checks.cfg:
   if (!mf_process_maxfwd_header("10")) {
       sl_send_reply("483","Too Many Hops");


    import_file "path_to_file"

Similar to include_file, but does not throw error if the included file is not found.


Control in C-style what parts of the config file are executed. The parts in non-defined zones are not loaded, ensuring lower memory usage and faster execution.

Available directives:

  • NAME - define a keyword
  • NAME VALUE - define a keyword with value
  • NAME - check if a keyword is defined
  • #!ifndef - check if a keyword is not defined
  • #!ifexp - check if an expression is true (see corresponding section for more)
  • #!else - switch to false branch of ifdef/ifndef/#!ifexp region
  • #!endif - end ifdef/ifndef/#!ifexp region
  • #!trydef - add a define if not already defined
  • #!redefine - force redefinition even if already defined

Predefined keywords:

  • KAMAILIO_X[_Y[_Z]] - Kamailio versions
  • MOD_X - when module X has been loaded
  • KAMAILIO_VERSION - associated with a number representation of Kamailio version (e.g., for version X.Y.Z, the value is X00Y00Z, representing X*1000000 + Y*1000 + z)
  • OS_NAME - associated with a string representing the Operating System name




See kamctl rpc core.ppdefines_full for full list.

Among benefits:

  • easy way to enable/disable features (e.g., see default cfg -- controlling support of nat traversal, presence, etc...)
  • switch control for parts where conditional statements were not possible (e.g., global parameters, module settings)
  • faster by not using conditional statements inside routing blocks when switching between running environments

Example: how to make config to be used in two environments, say testbed and production, controlled just by one define to switch between the two modes:





modparam("acc|auth_db|usrloc", "db_url",
modparam("acc|auth_db|usrloc", "db_url",


route[DEBUG] {
  xlog("SCRIPT: SIP $rm from: $fu to: $ru - srcip: $si"\n);


request_route {


  • you can define values for IDs
#!define MYINT 123
#!define MYSTR "xyz"
  • defined IDs are replaced at startup, during config parsing, e.g.,:
$var(x) = 100 + MYINT;
  • is interpreted as:
$var(x) = 100 + 123;
  • you can have multi-line defined IDs
#!define IDLOOP $var(i) = 0; \
                while($var(i)<5) { \
                    xlog("++++ $var(i)\n"); \
                    $var(i) = $var(i) + 1; \
  • then in routing block
request_route {
  • number of allowed defines is now set to 256
  • notes:
    • multilines defines are reduced to single line, so line counter should be fine
    • column counter goes inside the define value, but you have to omit the \ and CR for the accurate inside-define position
    • text on the same line as the directive will cause problems. Keep the directive lines clean and only comment on a line before or after.


Evaluate an expression and if true, then enable first region, otherwise enable the #!else region (if it exists).

The expression has to be till the end of the line (no support for multi-line yet).

The evaluation is done using snexpr (which is embedded inside Kamailio code):

Defined IDs can be used inside expressions with the following characteristics:

  • if there is an associated value, then the value is used as a string, with the enclosing quotes being removed
  • if there is no associated value, but the ID is defined, then the value 1 (integer) is used (equivalent of true)
  • if the ID is not defined, then the value 0 is used (equivalent of false)

The result of an expression is evaluated to:

  • true if it is a number different than 0
  • false if it is number 0
  • true if it is a string with length greater than 0
  • false if it is an empty string (length is 0)

Comparison operations between two strings are done using strcmp(s1, s2) and it is considered:

  • s1 < s2 - if the result of strcmp(s1, s2) is negative
  • s1 == s2 - if the result of strcmp(s1, s2) is 0
  • s1 > s2 - if the result of strcmp(s1, s2) is positive

Operations between two values with different types are done by converting the second value (right operand) to the type of the first value (left operand).


1 + "20" -> converted to: 1 + 20 (result: 21)
"1" + 20 -> converted to: "1" + "20" (result: "120")
4 > "20" -> converted to: 4 > 20 (result: false)
"4" > 20 -> converted to: "4" > "20" (result: true)

Available Operators

Arithmetic operations:

  • + - addition
  • - - subtraction
  • * - multiplication
  • / - division
  • % - modulus (remainder)
  • ** - power

Bitwise operations

  • << - shift left
  • >> - shift right
  • & - and
  • | - or
  • ^ - xor (unary bitwise negation)

Logical operations:

  • == - equal
  • != - not equal (different)
  • < - less than
  • > - greater than
  • <= - less than or equal to
  • >= - greater than or equal to
  • && - and
  • || - or
  • ! - unary not

String operations:

  • + - concatenation

Other operations:

  • = - assignment
  • ( ... ) - parenthesis to group parts of the expression
  • , - comma (separates expressions or function parameters)

ifexp examples

#!ifexp KAMAILIO_VERSION >= 5006000

#!ifexp MOD_xlog && (OS_NAME == "darwin")

#!define WITH_NAT




Preprocessor directive to define an ID to the value of an expression.

#!defenv ID STM

The evaluation of STM is done using snexpr, see the section for #!ifexp for more details about how the expression can be built, what data types and operators are supported.


#!define IPADDR

#!defexp SIPURI "sip:" + IPADDR + ":5060"
#!defexp QSIPURI '"sip:' + IPADDR + ':5060"'

#!defexp V16 1<<4


Preprocessor directive similar to #!defexp, but the the result being enclosed in double quotes, suitable to be used for string values.


Preprocessor directive to define an ID to the value of an environment variable with the name ENVVAR.

#!defenv ID=ENVVAR

It can also be just $!defenv ENVVAR and the defined ID is the ENVVAR name.


#!defenv SHELL

If environment variable $SHELL is '/bin/bash', then it is like:

#!define SHELL /bin/bash

Full expression variant:


Then it is like:

#!define ENVSHELL /bin/bash

It is a simplified alternative of using #!substdef with $env(NAME) in the replacement part.


Similar to #!defenv, but the value is defined in between double quotes to make it convenient to be used as a string token.

#!defenvs ENVVAR
#!defenvs ID=ENVVAR


#!trydefenv ID=ENVVAR

Similar to defenv, but will not error if the environmental variable is not set. This allows for boolean defines via system ENVVARs. For example, using an environmental variable to toggle loading of db_mysql:

#!trydefenv WITH_MYSQL

#!ifdef WITH_MYSQL
loadmodule ""


Similar to #!trydefenv, but the value is defined in between double quotes to make it convenient to be used as a string token.

#!trydefenvs ENVVAR
#!trydefenvs ID=ENVVAR


  • perform substitutions inside the strings of config (note that define is replacing only IDs - alphanumeric tokens not enclosed in quotes)
  • #!subst offers an easy way to search and replace inside strings before cfg parsing. E.g.,:
#!subst "/regexp/subst/flags"
  • flags is optional and can be: 'i' - ignore case; 'g' - global replacement


#!subst "/DBPASSWD/xyz/"
modparam("acc", "db_url", "mysql://user:DBPASSWD@localhost/db")
  • will do the substitution of db password in db_url parameter value


#!substdef "/ID/subst/"

Similar to #!subst, but in addition it adds a ID subst.


#!substdefs "/ID/subst/"

Similar to #!subst, but in addition it adds a ID "subst" (note the difference from #!substdef that the value for define is enclosed in double quotes, useful when the define is used in a place for a string value).

Core Keywords

Keywords specific to SIP messages which can be used mainly in if expressions.


The address family of the received SIP message. It is INET if the message was received over IPv4 or INET6 if the message was received over IPv6.

Exampe of usage:

    if (af==INET6) {
        log("Message received over IPv6 link\n");


The IP of the local interface where the SIP message was received. When the proxy listens on many network interfaces, makes possible to detect which was the one that received the packet.

Example of usage:

   if(dst_ip== {
      log("message received on loopback interface\n");


The local port where the SIP packet was received. When Kamailio is listening on many ports, it is useful to learn which was the one that received the SIP packet.

Example of usage:

       log("message was received on port 5061\n");


This script variable is a reference to the URI of 'From' header. It can be used to test 'From'- header URI value.

Example of usage:

    if(is_method("INVITE") && from_uri=~".*")
        log("the caller is from\n");


The variable is a reference to the SIP method of the message.

Example of usage:

       log("this SIP request is a REGISTER message\n");


The variable is a reference to the size of the message. It can be used in 'if' constructs to test message's size.

Example of usage:

        sl_send_reply("413", "message too large");



This variable can be used to test the transport protocol of the SIP message.

Example of usage:

        log("SIP message received over UDP\n");


If used in onreply_route, this variable is a referece to the status code of the reply. If it used in a standard route block, the variable is a reference to the status of the last reply sent out for the current request.

Example of usage:

        log("this is a 200 OK reply\n");






Reference to source IP address of the SIP message.

Example of usage:

        log("the message was sent from localhost!\n");


Reference to source port of the SIP message (from which port the message was sent by previous hop).

Example of usage:

        log("message sent from port 5061\n");




This variable can be used to test the value of URI from To header.

Example of usage:

      log("this is a request for users\n");


This variable can be used to test the value of the request URI.

Example of usage:

        log("this is a request for users\n");

Core Values

Values that can be used in 'if' expressions to check against Core Keywords


Variant: IPv4

This keyword can be used to test whether the SIP packet was received over an IPv4 connection.

Example of usage:

    if (af==INET) {
        log("the SIP message was received over IPv4\n");


Variant: IPv6

This keyword can be used to test whether the SIP packet was received over an IPv6 connection.

Example of usage:

      log("the SIP message was received over IPv6\n");


This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over SCTP or not.

Example of usage:

      log("the SIP message was received over SCTP\n");


This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over TCP or not.

Example of usage:

      log("the SIP message was received over TCP\n");


This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over TLS or not.

Example of usage:

      log("the SIP message was received over TLS\n");


This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over UDP or not.

Example of usage:

      log("the SIP message was received over UDP\n");


This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over WS or not.

Example of usage:

      log("the SIP message was received over WS\n");


This keyword can be used to test the value of 'proto' and check whether the SIP packet was received over WSS or not.

Example of usage:

      log("the SIP message was received over WSS\n");


Note: This command was removed.


This is a reference to the list of local IP addresses, hostnames and aliases that has been set in the Kamailio configuration file. This lists contain the domains served by Kamailio.

The variable can be used to test if the host part of an URI is in the list. The usefulness of this test is to select the messages that has to be processed locally or has to be forwarded to another server.

See "alias" to add hostnames, IP addresses and aliases to the list.

Example of usage:

    if(uri==myself) {
        log("the request is for local processing\n");

Note: You can also use the is_myself() function.

Core parameters


It can be an IP address or string and represents the address advertised in Via header. If empty or not set (default value) the socket address from where the request will be sent is used.

- don't set it unless you know what you are doing (e.g. nat traversal)
- you can set anything here, no check is made (e.g. will be accepted even if doesn't exist)

Example of usage:


Note: this option may be deprecated and removed in the near future, it is recommended to set advertise option for listen parameter.


The port advertised in Via header. If empty or not set (default value) the port from where the message will be sent is used. Same warnings as for 'advertised_address'.

Example of usage:


Note: this option may be deprecated and removed in the near future, it is recommended to set advertise option for listen parameter.


Alias name: domain

Parameter to set alias hostnames for the server. It can be set many times, each value being added in a list to match the hostname when 'myself' is checked.

It is necessary to include the port (the port value used in the "port=" or "listen=" defintions) in the alias definition otherwise the loose_route() function will not work as expected for local forwards. Even if you do not use 'myself' explicitly (for example if you use the domain module), it is often necessary to set the alias as these aliases are used by the loose_routing function and might be needed to handle requests with pre-loaded route set correctly.

Example of usage:

Note: the hostname has to be enclosed in between quotes if it has reserved tokens such as forward, drop ... or operators such as - (minus) ...


Specify how many child processes (workers) to create for asynchronous execution in the group "default". These are processes that can receive tasks from various components (e.g, modules such as async, acc, sqlops) and execute them locally, which is different process than the task sender.

Default: 0 (asynchronous framework is disabled).




Set the non-block mode for the internal sockets used by default group of async workers.

Default: 0




Set the number of microseconds to sleep before trying to receive next task (can be useful when async_nonblock=1).

Default: 0




Define groups of asynchronous worker processes.



The attributes are:

  • name - the group name (used by functions such as sworker_task(name))
  • workers - the number of processes to create for this group
  • nonblock - set or not set the non-block flag for internal communication socket
  • usleep - the number of microseconds to sleep before trying to receive next task (can be useful if nonblock=1)

Default: "".



If the name is default, then it overwrites the value set by async_workers.

See also event_route[core:pre-routing] and sworker module.


Alias name: auto_domains

Kamailio by default discovers all IPv4 addresses on all interfaces and does a reverse DNS lookup on these addresses to find host names. Discovered host names are added to aliases list, matching the myself condition. To disable host names auto-discovery, turn off auto_aliases.





When turned on, Kamailio will automatically bind to all IPv6 addresses (much like the default behaviour for IPv4). Default is 0.



If set to 1, try to bind also IPv6 link local addresses by discovering the scope of the interface. This apply for UDP socket for now, to be added for the other protocols. Default is 0.




Check if the address in top most via of replies is local. Default value is 0 (check disabled).

Example of usage:



Number of children to fork for the UDP interfaces (one set for each interface - ip:port). Default value is 8. For example if you configure the proxy to listen on 3 UDP ports, it will create 3xchildren processes which handle the incoming UDP messages.

For configuration of the TCP/TLS worker threads see the option "tcp_children".

Example of usage:



The value must be a valid path in the system. If set, Kamailio will chroot (change root directory) to its value.

Example of usage:



Set the debug level used to print some log messages from core, which might become annoying and don't represent critical errors. For example, such case is failure to parse incoming traffic from the network as SIP message, due to someone sending invalid content.

Default value is -1 (L_ERR).

Example of usage:



Set the debug level. Higher values make Kamailio to print more debug messages. Log messages are usually sent to syslog, except if logging to stderr was activated (see #log_stderror parameter).

The following log levels are defined:

     L_ALERT     -5
     L_BUG       -4
     L_CRIT2     -3
     L_CRIT      -2
     L_ERR       -1
     L_WARN       0 
     L_NOTICE     1 
     L_INFO       2 
     L_DBG        3 

A log message will be logged if its log-level is lower than the defined debug level. Log messages are either produced by the the code, or manually in the configuration script using log() or xlog() functions. For a production server you usually use a log value between -1 and 2.

Default value: L_WARN (debug=0)

Examples of usage:

  • debug=3: print all log messages. This is only useful for debugging of problems. Note: this produces a lot of data and therefore should not be used on production servers (on a busy server this can easily fill up your hard disk with log messages)
  • debug=0: This will only log warning, errors and more critical messages.
  • debug=-6: This will disable all log messages.

Value of 'debug' parameter can also be obtained and set dynamically using the 'debug' Core MI function or the RPC function, e.g.:

    kamcmd cfg.get core debug
    kamcmd cfg.set_now_int core debug 2
    kamcmd cfg.set_now_int core debug -- -1

Note: There is a difference in log-levels between Kamailio 3.x and Kamailio\<=1.5: Up to Kamailio 1.5 the log level started with 4, whereas in Kamailio>=3 the log level starts with 3. Thus, if you were using debug=3 in older Kamailio, now use debug=2.

For configuration of logging of the memory manager see the parameters #memlog and #memdbg.

Further information can also be found at:


Alias name: descr desc


Can be 'yes' or 'no'. By default core dump limits are set to unlimited or a high enough value. Set this config variable to 'yes' to disable core dump-ing (will set core limits to 0).

Default value is no.

Example of usage:



Alias name: tls_disable

Global parameter to disable TLS support in the SIP server. Default value is 'yes'.

Note: Make sure to load the "tls" module to get tls functionality.

Example of usage:


In Kamailio TLS is implemented as a module. Thus, the TLS configuration is done as module configuration. For more details see the README of the TLS module:


Alias name: tls_enable

Reverse Meaning of the disable_tls parameter. See disable_tls parameter.

    enable_tls=yes # enable tls support in core


Alias name: ser_kill_timeout

How much time Kamailio will wait for all the shutdown procedures to complete. If this time is exceeded, all the remaining processes are immediately killed and Kamailio exits immediately (it might also generate a core dump if the cleanup part takes too long).

Default: 60 s. Use 0 to disable.

     exit_timeout = seconds


SIP message (transaction) flags can have string names. The name for flags cannot be used for branch or script flags(*)

  FLAG_ONE   : 1,
  FLAG_TWO   : 2;
  • NOTE: The named flags feature was propagated from the source code merge back in 2008 and is not extensively tested. The recommended way of defining flags is using #!define (which is also valid for branch/script flags):


yes/no: Similar to the force_rport() function, but activates symmetric response routing globally.


If set to 'yes' the proxy will fork and run in daemon mode - one process will be created for each network interface the proxy listens to and for each protocol (TCP/UDP), multiplied with the value of 'children' parameter.

When set to 'no', the proxy will stay bound to the terminal and runs as single process. First interface is used for listening to. This is equivalent to setting the server option "-F".

Default value is 'yes'.

Example of usage:



Number of usecs to wait before forking a process.

Default is 0 (don't wait).

Example of usage:



Alias name: gid

The group id to run Kamailio.

Example of usage:



Alias: http_reply_hack

When enabled, Kamailio can parse HTTP replies, but does so by treating them as SIP replies. When not enabled HTTP replies cannot be parsed. This was previously a compile-time option, now it is run-time.

Default value is 'no'.

Example of usage:



Alias: ipfreebind, ip_nonlocal_bind

Control if Kamailio should attempt to bind to non local ip. This option is the per-socket equivalent of the system ip_nonlocal_bind.

Default is 0 (do not bind to non local ip).

Example of usage:

  ip_free_bind = 1


Can be set to a, A or c to specify if locally computed string representation of IPv6 addresses should be expanded lowercase, expanded uppercase or compacted lowercase hexa digits.

Default is c (compacted lower hexa digits, conforming better with RFC 5952).

A is preserving the behaviour before this global parameter was introduced, while a enables the ability to follow some of the recommendations of RFC 5952, section 4.3.

Example of usage:

  ipv6_hex_style = "a"


Set the name of callback function in the KEMI script to be executed as the equivalent of onsend_route block (from the native configuration file).

Default value: ksr_onsend_route

Set it to empty string or none to skip execution of this callback function.




Set the name of callback function in the KEMI script to be executed as the equivalent of event_route[core:msg-received] block (from the native configuration file). For execution, it also require to have the received_route_mode global parameter set to 1.

Default value: none

Set it to empty string or none to skip execution of this callback function.




Set the name of callback function in the KEMI script to be executed as the equivalent of reply_route block (from the native configuration file).

Default value: ksr_reply_route

Set it to empty string or none to skip execution of this callback function.




Set the name of callback function in the KEMI script to be executed as the equivalent of event_route[core:pre-routing] block (from the native configuration file).

Default value: none

Set it to empty string or none to skip execution of this callback function.




If set to a log level less or equal than debug parameter, a log message with the duration in microseconds of executing request route or reply route is printed to syslog.

Default value is 3 (L_DBG).




Limit of latency in us (micro-seconds) for config actions. If a config action executed by cfg interpreter takes longer than its value, a message is printed in the logs, showing config path, line and action name when it is a module function, as well as internal action id.

Default value is 0 (disabled).



Limit of latency in us (micro-seconds) for db operations. If a db operation executed via DB API v1 takes longer that its value, a message is printed in the logs, showing the first 50 characters of the db query.

Default value is 0 (disabled).



Log level to print the messages related to latency.

Default value is -1 (L_ERR).



Set the network addresses the SIP server should listen to. It can be an IP address, hostname or network interface id or combination of protocol:address:port (e.g., udp: This parameter can be set multiple times in same configuration file, the server is listening on all addresses specified.

Example of usage:


If you omit this directive then the SIP server will listen on all network interfaces. On start the SIP server reports all the interfaces that it is listening on. Even if you specify only UDP interfaces here, the server will start the TCP engine too. If you don't want this, you need to disable the TCP support completely with the core parameter disable_tcp.

If you specify IPv6 addresses, you should put them into square brackets, e.g.:


You can specify an advertise address (like ip:port) per listening socket - it will be used to build the SIP headers such as Via and Record-Route:

    listen=udp: advertise

The advertise address must be in the format address:port, the protocol is taken from the bind socket. The advertise address is a convenient alternative to advertised_address / advertised_port config parameters or set_advertised_address() / set_advertised_port() config functions.

A typical use case for advertise address is when running SIP server behind a NAT/Firewall, when the local IP address (to be used for bind) is different than the public IP address (to be used for advertising).

A unique name can be set for sockets to simplify the selection of the socket for sending out. For example, the rr and path modules can use the socket name to advertise it in header URI parameter and use it as a shortcut to select the corresponding socket for routing subsequent requests.

The name has to be provided as a string enclosed in between quotes after the name keyword.

    listen=udp: name "s1"
    listen=udp: advertise name "s2"
    listen=udp: advertise "" name "s3"
    listen=udp: advertise "" name "s4"
    $fsn = "s4";

Note that there is no internal check for uniqueness of the socket names, the admin has to ensure it in order to be sure the desired socket is selected, otherwise the first socket with a matching name is used.

As of 5.6, there is now a virtual keyword which can be added to the end of each listen directive. This can be used in combination with any other keyword, but must be added at the end of the line.

    listen=udp: virtual
    listen=udp: name "s1" virtual
    listen=udp: advertise virtual
    listen=udp: advertise "" name "s3" virtual

The virtual keyword is meant for use in situations where you have a floating/virtual IP address on your system that may not always be active on the system. It is particularly useful for active/active virtual IP situations, where otherwise things like usrloc PATH support can break due to incorrect check_self results.

This identifier will change the behaviour of how myself, is_myself() or check_self matches against traffic destined to this IP address. By default, Kamailio always considers traffic destined to a listen IP as local regardless of if the IP is currently locally active. With this flag set, Kamailio will do an extra check to make sure the IP is currently a local IP address before considering the traffic as local.

This means that if Kamailio is listening on an IP that is not currently local, it will recognise that, and can relay the traffic to another Kamailio node as needed, instead of thinking it always needs to handle the traffic.


Loads a module for later usage in the configuration script. The module is searched in the path specified by loadpath (or mpath).


  • loadmodule "modulepath"
  • loadmodule("modulepath")
  • loadmodule("modulepath", "opts")

If modulepath is only modulename or, then Kamailio will try to search also for modulename/, very useful when using directly the version compiled in the source tree.

The opts parameter is a list of characters that can specify loading options. They can be:

  • g (or G) - open the module shared object file with RTLD_GLOBAL set, which can be used for modules related to external scripting languages to avoid reloading.

Example of usage:

    loadpath "/usr/local/lib/kamailio/:usr/local/lib/kamailio/modules/"

    loadmodule "/usr/local/lib/kamailio/modules/"
    loadmodule "modules/"
    loadmodule "tm"
    loadmodule ""
    loadmodule("", "g")


Similar to loadmodule with the ability to evaluate variables in its parameter.


Alias name: mpath

Set the module search path. loadpath takes a list of directories separated by :. The list is searched in-order. For each directory d, $d/${module_name}.so and $d/${module_name}/${module_name}.so are tried.

This can be used to simplify the loadmodule parameter and can include many paths separated by colon. First module found is used.

Example of usage:

    loadpath "/usr/local/lib/kamailio/modules:/usr/local/lib/kamailio/mymodules"

    loadmodule "mysql"
    loadmodule "uri"
    loadmodule "uri_db"
    loadmodule "sl"
    loadmodule "tm"

The proxy tries to find the modules in a smart way, e.g: loadmodule "uri" tries to find in the loadpath, but also uri/


Similar to add_local_rport() function, but done in a global scope, so the function does not have to be executed for each request.

Default: off


local_rport = on


Set specific data required by the log engine. See also the log_engine_type.



Specify what logging engine to be used and its initialization data. A logging engine is implemented as a module. Supported values are a matter of the module.

For example, see the readme of log_custom module for more details.



If Kamailio logs to syslog, you can control the facility for logging. Very useful when you want to divert all Kamailio logs to a different log file. See the man page syslog(3) for more details.

For more see:

Default value is LOG_DAEMON.

Example of usage:



Allows to configure a log_name prefix which will be used when printing to syslog -- it is also known as syslog tag, and the default value is the application name or full path that printed the log message. This is useful to filter log messages when running many instances of Kamailio on same server.



Specify the text to be prefixed to the log messages printed by Kamailio while processing a SIP message (that is, when executing route blocks). It can contain script variables that are evaluated at runtime. See #log_prefix_mode about when/how evaluation is done.

If a log message is printed from a part of the code executed out of routing blocks actions (e.g., can be timer, evapi worker process, ...), there is no log prefix set, because this one requires a valid SIP message structure to work with.

Example - prefix with message type (1 - request, 2 - response), CSeq and Call-ID:

    log_prefix="{$mt $hdr(CSeq) $ci} "


Control if log prefix is re-evaluated.

If set to 0 (default), then log prefix is evaluated when the sip message is received and then reused (recommended if the log_prefix has only variables that have same value for same message). This is the current behaviour of log_prefix evaluation.

If set to 1, then the log prefix is evaluated before/after each config action (needs to be set when the log_prefix has variables that are different based on the context of config execution, e.g., $cfg(line)).




With this parameter you can make Kamailio to write log and debug messages to standard error. Possible values are:

  • yes - write the messages to standard error
  • no - write the messages to syslog

Default value is no.

For more see:

Example of usage:



Set the config interpreter engine for execution of the routing logic inside the configuration file. Default is the native interpreter.

Example of usage:

    cfgengine "name"

If name is native or default, it expects to have in native config interpreter for routing logic.

The name can be the identifier of an embedded language interpreter, such as lua which is registered by the app_lua module:

    cfgengine "lua"


The size in bytes not to be exceeded during the auto-probing procedure of discovering and increasing the maximum OS buffer size for receiving UDP messages (socket option SO_RCVBUF). Default value is 262144.

Example of usage:


Note: it is not the size of the internal SIP message receive buffer.


The maximum number of outgoing branches for each SIP request. It has impact on the size of destination set created in core (e.g., via append_branch()) as well as the serial and parallel forking done via tm module. It replaces the old defined constant MAX_BRANCHES.

The value has to be at least 1 and the upper limit is 30.

Default value: 12

Example of usage:



The parameters set the value of maximum recursive calls to blocks of actions, such as sub-routes or chained IF-ELSE (for the ELSE branches). Default is 256.

Example of usage:



The parameters set the value of maximum loops that can be done within a "while". Comes as a protection to avoid infinite loops in config file execution. Default is 100. Setting to 0 disables the protection (you will still get a warning when you start Kamailio if you do something like while(1) {...}).

Example of usage:



This parameter can be used to set the interface that should join the multicast group. This is useful if you want to listen on a multicast address and don't want to depend on the kernel routing table for choosing an interface.

The parameter is reset after each listen parameter, so you can join the right multicast group on each interface without having to modify kernel routing beforehand.

Example of usage:



It can be 'yes' or 'no'. If set to 'yes', multicast datagram are sent over loopback. Default value is 'no'.

Example of usage:



Set the value for multicast ttl. Default value is OS specific (usually 1).

Example of usage:



Alias name: mem_dbg

This parameter specifies on which log level the memory debugger messages will be logged. If memdbg is active, every request (alloc, free) to the memory manager will be logged. (Note: if compile option NO_DEBUG is specified, there will never be logging from the memory manager).

Default value: L_DBG (memdbg=3)

For example, memdbg=2 means that memory debugging is activated if the debug level is 2 or higher.

    debug=3    # no memory debugging as debug level 
    memdbg=4   # is lower than memdbg

    debug=3    # memory debugging is active as the debug level 
    memdbg=2   # is higher or equal memdbg

Please see also #memlog and #debug.


Alias name: mem_log

This parameter specifies on which log level the memory statistics will be logged. If memlog is active, Kamailio will log memory statistics on shutdown (or if requested via signal SIGUSR1). This can be useful for debugging of memory leaks.

Default value: L_DBG (memlog=3)

For example, memlog=2 means that memory statistics dumping is activated if the debug level is 2 or higher.

    debug=3    # no memory statistics as debug level 
    memlog=4   # is lower than memlog

    debug=3    # dumping of memory statistics is active as the 
    memlog=2   # debug level is higher or equal memlog

Please see also #memdbg and #debug.


If set to 1, memory manager (e.g., q_malloc) does join of free fragments. It is effective if MEM_JOIN_FREE compile option is defined.

It can be set via config reload framework.

Default is 1 (enabled).


To change its value at runtime, kamcmd needs to be used and the modules ctl and cfg_rpc loaded. Enabling it can be done with:

    kamctl rpc cfg.set_now_int core mem_join 1

To disable, set its value to 0.


If set to 1, memory free operation does not call abort() for double freeing a pointer or freeing an invalid address. The server still prints the alerting log messages. If set to 0, the SIP server stops by calling abort() to generate a core file.

It can be set via config reload framework.

Default is 1 (enabled).



If set to 1, memory status dump for qm allocator will print details about used fragments. If set to 0, the dump contains only free fragments. It can be set at runtime via cfg param framework (e.g., via kamcmd).

Default is 0.



Parameter to control printing of memory debugging information displayed on exit or SIGUSR1. The value can be composed by following flags:

  • 1 - dump all the pkg used blocks (status)
  • 2 - dump all the shm used blocks (status)
  • 4 - summary of pkg used blocks
  • 8 - summary of shm used blocks
  • 16 - short status

If set to 0, nothing is printed.

Default value: 12




Set the server to try to locate outbound interface on multihomed host. This parameter affects the selection of the outgoing socket for forwarding requests. By default is off (0) - it is rather time consuming. When deactivated, the incoming socket will be used or the first one for a different protocol, disregarding the destination location. When activated, Kamailio will select a socket that can reach the destination (to be able to connect to the remote address). (Kamailio opens a UDP socket to the destination, then it retrieves the local IP which was assigned by the operating system to the new UDP socket. Then this socket will be closed and the retrieved IP address will be used as IP address in the Via/Record-Route headers)

Example of usage:



Locks all Kamailio pages into memory making it unswappable (in general one doesn't want his SIP proxy swapped out :-))

    mlock_pages = yes |no (default no)


Number of microseconds to wait after initializing a module - useful to cope with systems where are rate limits on new connections to database or other systems.

Default value is 0 (no wait).



The modparam command will be used to set the options (parameters) for the loaded modules.


modparam("modname", "paramname", intval)
modparam("modname", "paramname", "strval")

The first pameter is the name of the module or a list of module names separated by | (pipe). Actually, the modname is enclosed in beteen ^( and )$ and matched with the names of the loaded modules using POSIX regexp operation. For example, when auth is given, then the module name is matched with ^(auth)$; when acc|auth is given, then the module name is matched with ^(acc|auth)$. While using only | between the names of the modules is recommended for clarity, any value that can construct a valid regular expression can be used. Note also that modparam throws error only when no module name is matched and no parameter is set. If the list of modules in modname includes a wrong name, Kamailio starts. For example setting modname to msilo|notamodule does not result in a startup error if msilo module is loaded. Be also careful with expressions than can match more module names than wanted, for example setting modname to a|b can result in matching all module names that include either a or b.

The second parameter of modparam is the name of the module parameter.

The third parameter of modparam has to be either an interger or a string value, a matter of what the module parameter expects, as documented in the README of the module.


    modparam("usrloc", "db_mode", 2)
    modparam("usrloc", "nat_bflag", 6)
    modparam("auth_db|msilo|usrloc", "db_url",

See the documenation of the respective module to find out the available options.


Similar to modparam, with ability to evaluate the variables in its parameters.


If set to 1 (yes, on), onsend_route block is executed for received replies that are sent out. Default is 0.



If set and bigger than the current open file limit, Kamailio will try to increase its open file limit to this number. Note: Kamailio must be started as root to be able to increase a limit past the hard limit (which, for open files, is 1024 on most systems). "Files" include network sockets, so you need one for every concurrent session (especially if you use connection-oriented transports, like TCP/TLS).

Example of usage:



By enabling this feature, Kamailio internally treats SIP URIs with user=phone parameter as TEL URIs. If you do not want this behavior, you have to turn it off.

Default value: 1 (enabled)

    phone2tel = 0


If set to 1, the don't-fragment (DF) bit will be set in outbound IP packets, but no fragmentation from the kernel will be done for IPv4 and IPv6. This means that packets might be dropped and it is up to the user to reduce the packet size and try again.

If set to 2, the kernel will will fragment a packet if needed according to the path MTU, or will set the don't-fragment flag otherwise. For IPv6 the kernel will fragment a packet if needed according to the path MTU. The kernel keeps track of the path MTU per destination host.

The default is 0, do not set the don't-fragment bit or fragment packets for IPv4 and IPv6.

    pmtu_discovery = 0 | 1 | 2 (default 0)


The port the SIP server listens to. The default value for it is 5060.

Example of usage:



The size in bytes of internal buffer to print dynamic strings with pseudo-variables inside. The default value is 8192 (8kB). Please keep in mind that for xlog messages, there is a dedicated module parameter to set the internal buffer size.

Example of usage:



The number of internal buffer slots to print dynamic strings with pseudo-variables inside. The default value is 10.

Example of usage:



The limit how many pv declarations in the cache after which an action is taken. Default value is 2048.



Specify what action to be done when the size of pv cache is exceeded. If 0, print a warning log message when the limit is exceeded. If 1, warning log messages is printed and the cache systems tries to drop a $sht(...) declaration. Default is 0.



Specify the time interval (in seconds) required to wait before executing again an RPC command exported with the flag RPC_EXEC_DELTA. Practically it enables an execution rate limit for such command. The rate limiting is per RPC command.

Such RPC commands can be those related to reload of data records or config options from backends such as database or hard drive. For them, executing the RPC command too ofter can result in compromizing the internal structures (e.g., previous reload of data was not finished when next reload is triggered).

Default value: 0 (no rate limiting)




Alias: run_dir

Set the folder for creating runtime files such as MI fifo or CTL unixsocket.

Default: /var/run/kamailio

Example of usage:



Enable or disable the execution of event_route[core:msg-received] routing block or its corresponding Kemi callback.

Default value: 0 (disabled)

Example of usage:



If it is set to 1, any local reply is sent to the IP address advertised in top most Via of the request instead of the IP address from which the request was received. Default value is 0 (off).

Example of usage:



Set the number of mutex locks to be used for synchronizing the execution of config script for messages sharing the same Call-Id. In other words, enables Kamailio to execute the config script sequentially for the requests and replies received within the same dialog -- a new message received within the same dialog waits until the previous one is routed out.

For smaller impact on parallel processing, its value it should be at least twice the number of Kamailio processes (all children processes).


route_locks_size = 256

Note that ordering of the SIP messages can still be changed by network transmission (quite likely for UDP, especially on long distance paths) or CPU allocation for processes when executing pre-config and post-config tasks (very low chance, but not to be ruled out completely).


A configurable unique server id that can be used to discriminate server instances within a cluster of servers when all other information, such as IP addresses are the same.

  server_id = number


Set the value of Server header for replies generated by Kamailio. It must contain the header name, but not the ending CRLF.

Example of usage:

server_header="Server: My Super SIP Server"


This parameter controls the "Server" header in any locally generated message.

Example of usage:


If it is enabled (default=yes) a header is generated as in the following example:

    Server: Kamailio (<version> (<arch>/<os>))


Tries to pre-fault all the shared memory, before starting. When "on", start time will increase, but combined with mlock_pages will guarantee Kamailio will get all its memory from the beginning (no more kswapd slow downs)

shm_force_alloc = yes | no (default no)


Set shared memory size (in Mb).

shm_mem_size = 64 (default 64)


Log level for printing debug messages for some of the SIP parsing errors.

Default: 0 (L_WARN)

sip_parser_log = 1


Control sip parser behaviour.

If set to 1, the parser is more strict in accepting messages that have invalid headers (e.g., duplicate To or From). It can make the system safer, but loses the flexibility to be able to fix invalid messages with config operations.

If set to 0, the parser is less strict on checking validity of headers.

Default: 1

sip_parser_mode = 0

sip_warning (noisy feedback)

Can be 0 or 1. If set to 1 (default value is 0) a 'Warning' header is added to each reply generated by Kamailio. The header contains several details that help troubleshooting using the network traffic dumps, but might reveal details of your network infrastructure and internal SIP routing.

Example of usage:



Specify an address to listen (bind) to, a simplified alternative to listen paramter that allows specifying the attributes using a structure style.


socket = {
    attr1 = value1;
    attrN = valueN;

The attributes are:

  • bind - the address to listen on in format [proto:]address[:port]
  • advertise - the address to advertise in SIP headers in format address[:port]
  • name - name of the socket to be referenced in configuration file
  • virtual - set to yes/no to indicate if the IP has to be considered virtual or not

The attribute bind is mandatory and has to provide at list the address to listen on.


socket = {
    bind = udp:;
    advertise =;
    name = "s0";
    virtual = yes;

The above is the equivalent of:

listen=udp: advertise name "s0" virtual


Number of workers to process SIP traffic per listen socket - typical use is before a listen global parameter.

  • when used before listen on UDP or SCTP socket, it overwrites children or sctp_children value for that socket.
  • when used before listen on TCP or TLS socket, it adds extra tcp workers, these handling traffic only on that socket.

The value of socket_workers is reset with next listen socket definition that is added, thus use it for each listen socket where you want custom number of workers.

If this parameter is not used at all, the values for children, tcp_children and sctp_children are used as usually.

Example for udp sockets:

  • it will start 2 workers to handle traffic on udp: and 4 for each of udp: and udp: In total there are 10 worker processes

Example for tcp sockets:

  • it will start 2 workers to handle traffic on tcp: and 4 to handle traffic on both tcp: and tcp: In total there are 6 worker processes


The size in bytes of the SQL buffer created for data base queries. For database drivers that use the core db_query library, this will be maximum size object that can be written or read from a database. Default value is 65535.

Example of usage:



Kamailio has built-in support for statistics counter. This means, these counters can be increased, decreased, read and cleared. The statistics counter are defined either by the core (e.g. tcp counters), by modules (e.g. 2xx_transactions by "tmx" module) or by the script writer using the "statistics" module.

The statistics counters are read/updated either automatically by Kamailio internally (e.g. tcp counters), by the script writer via the module functions of the "statistics" module, by the script writer using the $stat() pseudo variable (read-only), or via MI commands.

Following are some examples how to access statistics variables:


    modparam("statistics", "variable", "NOTIFY")

    (if method == "NOTIFY") {
      update_stat("NOTIFY", "+1");

    xlog("Number of received NOTIFYs: $stat(NOTIFY)");


    # get counter value
    kamctl rpc stats.get_statistics NOTIFY
    # set counter to zero
    kamctl rpc stats.reset_statistics NOTIFY
    # get counter value and then set it to zero
    kamctl rpc stats.clear_statistics NOTIFY

    # or use the kamcmd tool
    kamcmd stats.get_statistics 1xx_replies


Specify the character used as a separator for the internal statistics' names. Default value is _.

Example of usage:

    stats_name_separator = "-"


The TOS (Type Of Service) to be used for the sent IP packages (both TCP and UDP).

Example of usage:



Fallback to another protocol (udp_mtu_try_proto must be set also either globally or per packet) if the constructed request size is greater than udp_mtu.

RFC 3261 specified size: 1300. Default: 0 (off).

    udp_mtu = number


If udp_mtu != 0 and udp forwarded request size (after adding all the "local" headers) > udp_mtu, use this protocol instead of udp. Only the Via header will be updated (e.g. The Record-Route will be the one built for udp).

Warning: Although RFC3261 mandates automatic transport protocol changing, enabling this feature can lead to problems with clients which do not support other protocols or are behind a firewall or NAT. Use this only when you know what you do!

See also udp_mtu_try_proto(proto) function.

Default: UDP (off). Recommended: TCP.

    udp_mtu_try_proto = TCP|TLS|SCTP|UDP


Specify additional chars that should be allowed in the host part of URI.

uri_host_extra_chars = "_"


Alias name: uid

The user id to run Kamailio (Kamailio will suid to it).

Example of usage:



Set the value of User-Agent header for requests generated by Kamailio. It must contain header name as well, but not the ending CRLF.

user_agent_header="User-Agent: My Super SIP Server"


Control if printing routing tree and udp probing buffer debug messages should be printed at startup.

Default is 0 (don't print); set to 1 to get those debug messages.

Example of usage:



Set the name of the table holding the table version. Useful if the proxy is sharing a database within a project and during upgrades. Default value is "version".

Example of usage:



Enable waiting for child SIP worker one to complete initialization, then create the other child worker processes.

Default: 0 (do not wait for child worker one to complete initialization).


wait_worker1_mode = 1


How long to wait for child worker one to complete the initialization. In micro-seconds.

Default: 4000000 (micro-seconds = 4 seconds).


wait_worker1_time = 1000000


Waiting for child worker one to complete the initialization is done in a loop, which loop waits until wait_worker1_time passes. This parameter specifies how long after each iteration of that loop to wait in micro-seconds.

Default: 100000 (micro-seconds = 0.1 seconds).


wait_worker1_usleep = 50000


Alias name: wdir

The working directory used by Kamailio at runtime. You might find it useful when it comes to generating core files :)

Example of usage:

    # or


Set the name of the XAVP of which subfields will be added as local Via -header parameters.

If not set, XAVP to Via header parameter manipulation is not applied (default behaviour).

If set, local Via header gets additional parameters from defined XAVP. Core flag FL_ADD_XAVP_VIA_PARAMS needs to be set¹.



[1] See function via_add_xavp_params() from "corex" module.


Set the name of xavp from where to take Via header field: address and port. Use them to build local Via header.



request_route {
  $xavp(customvia=>address) = "";
  $xavp(customvia[0]=>port) = "5080";  # must be string

See function via_use_xavp_fields() from "corex" module.


Set the name of the XAVP of which subfields will be added as header parameters to the top Via of the replies sent out.

If not set, XAVP to Via header parameter manipulation is not applied (default behaviour).

If set, top Via header of the to-be-sent reply gets additional parameters from defined XAVP. Core flag FL_ADD_XAVP_VIA_REPLY PARAMS needs to be set¹.



[1] See function via_reply_vadd_xavp_params() from "corex" module.

DNS Parameters

Note: See also file doc/tutorials/dns.txt for details about Kamailio's DNS client.

Kamailio has an internal DNS resolver with caching capabilities. If this caching resolver is activated (default setting) then the system's stub resolver won't be used. Thus, also local name resolution configuration like /etc/hosts entries will not be used. If the DNS cache is deactivated (use_dns_cache=no), then system's resolver will be used. The DNS failover functionality in the tm module references directly records in the DNS cache (which saves a lot of memory) and hence DNS based failover only works if the internal DNS cache is enabled.

DNS resolver comparison internal resolver system resolver
Caching of resolved records yes no*
NAPTR/SRV lookups with correct weighting yes yes
DNS based failover yes no
  • Of course you can use the resolving name servers configured in /etc/resolv.conf as caching nameservers.

If the internal resolver/cache is enabled you can add/remove records by hand (using kamcmd or xmlrpc) using the DNS RPCs, e.g. dns.add_a, dns.add_srv, dns.delete_a a.s.o. For more info on DNS RPCs see:

Note: During startup of Kamailio, before the internal resolver is loaded, the system resolver will be used (it will be used for queries done from module register functions or modparams fixups, but not for queries done from mod_init() or normal fixups).

Note: The dns cache uses the DNS servers configured on your server (/etc/resolv.conf), therefore even if you use the internal resolver you should have a working DNS resolving configuration on your server.

Kamailio also allows you to finetune the DNS resolver settings.

The maximum time a dns request can take (before failing) is (if dns_try_ipv6 is yes, multiply it again by 2; if SRV and NAPTR lookups are enabled, it can take even longer!):


Note: During DNS lookups, the process which performs the DNS lookup blocks. To minimize the blocked time the following parameters can be used (max 2s):



This parameter controls if the SIP server will try doing a DNS lookup on the address in the Via header of a received sip request to decide if adding a received=src_ip parameter to the Via is necessary. Note that Vias containing DNS names (instead of IPs) should have received= added, so turning dns to yes is not recommended.

Default is no.


Alias Name: dns_rev_via

This parameter controls if the SIP server will try doing a reverse DNS lookup on the source IP of a sip request to decide if adding a received=src_ip parameter to the Via is necessary (if the Via contains a DNS name instead of an IP address, the result of the reverse dns on the source IP will be compared with the DNS name in the Via). See also dns (the effect is cumulative, both can be turned on and in that case if the DNS lookup test fails the reverse DNS test will be tried). Note that Vias containing DNS names (instead of IPs) should have received= added, so turning rev_dns to yes is not recommended.

Default is no.


Alias name: dns_cache_delete_nonexpired

    dns_cache_del_nonexp = yes | no (default: no)
  allow deletion of non-expired records from the cache when there is no more space
  left for new ones. The last-recently used entries are deleted first.


    dns_cache_rec_pref = number (default 0)
  dns cache record preference, determines how new DNS records are stored internally in relation to existing entries.
  Possible values:
    0 - do not check duplicates
    1 - prefer old records
    2 - prefer new records
    3 - prefer records with longer lifetime


    dns_cache_flags = number (default 0)
  dns cache specific resolver flags, used for overriding the default behaviour (low level).
  Possible values:
    1 - ipv4 only: only DNS A requests are performed, even if Kamailio also listens on ipv6 addresses.
    2 - ipv6 only: only DNS AAAA requests are performed. Ignored if dns_try_ipv6 is off or Kamailio 
        doesn't listen on any ipv6 address.
    4 - prefer ipv6: try first to resolve a host name to an ipv6 address (DNS AAAA request) and only
        if this fails try an ipv4 address (DNS A request). By default the ipv4 addresses are preferred.


Interval in seconds after which the dns cache is garbage collected (default: 120 s)

    dns_cache_gc_interval = number


If off, the dns cache is not initialized at startup and cannot be enabled at runtime, this saves some memory.

    dns_cache_init = on | off (default on)


    dns_cache_max_ttl = time in seconds (default MAXINT)


Maximum memory used for the dns cache in KB (default 500 K)

    dns_cache_mem = number


    dns_cache_min_ttl = time in seconds (default 0)


Tells how long to keep negative DNS responses in cache. If set to 0, disables caching of negative responses. Default is 60 (seconds).


If the DNS lookup should ignore the remote side's protocol preferences, as indicated by the Order field in the NAPTR records and mandated by RFC 2915.

      dns_naptr_ignore_rfc = yes | no (default yes)


Number of dns retransmissions before giving up. Default value is system specific, depends also on the '/etc/resolv.conf' content (usually 4).

Example of usage:



Time in seconds before retrying a dns request. Default value is system specific, depends also on the '/etc/resolv.conf' content (usually 5s).

Example of usage:



When name was resolved using dns search list, check the domain added in the answer matches with one from the search list (small performance hit, but more safe)

    dns_search_full_match = yes | no (default yes)


How many dns servers from the ones defined in '/etc/resolv.conf' will be used. Default value is to use all of them.

Example of usage:



Alias name: dns_srv_loadbalancing

Enable dns srv weight based load balancing (see doc/tutorials/dns.txt)

    dns_srv_lb = yes | no (default no)


Can be 'yes' or 'no'. If it is set to 'yes' and a DNS lookup fails, it will retry it for ipv6 (AAAA record). Default value is 'no'.

Note: If dns_try_ipv6 is off, no hostname resolving that would result in an ipv6 address would succeed - it doesn't matter if an actual DNS lookup is to be performed or the host is already an ip address. Thus, if the proxy should forward requests to IPv6 targets, this option must be turned on!

Example of usage:



Enable NAPTR support according to RFC 3263 (see doc/tutorials/dns.txt for more info)

    dns_try_naptr = yes | no (default no)

dns_sctp_pref, dns_tcp_pref, dns_tls_pref, dns_udp_pref

Alias name: dns_sctp_preference, dns_tcp_preference, dns_tls_preference, dns_udp_preference

Set preference for each protocol when doing naptr lookups. By default dns_udp_pref=30, dns_tcp_pref=20, dns_tls_pref=10 and dns_sctp_pref=20. To use the remote site preferences set all dns_*_pref to the same positive value (e.g. dns_udp_pref=1, dns_tcp_pref=1, dns_tls_pref=1, dns_sctp_pref=1). To completely ignore NAPTR records for a specific protocol, set the corresponding protocol preference to -1 (or any other negative number). (see doc/tutorials/dns.txt for more info)

    dns_{udp,tcp,tls,sctp}_pref = number


Can be 'yes' or 'no'. If set to 'no', the search list in '/etc/resolv.conf' will be ignored (=> fewer lookups => gives up faster). Default value is 'yes'.

HINT: even if you don't have a search list defined, setting this option to 'no' will still be "faster", because an empty search list is in fact search "" (so even if the search list is empty/missing there will still be 2 dns queries, eg. foo+'.' and foo+""+'.')

Example of usage:



Alias name: dns_use_cache

Tells if DNS responses are cached - this means that the internal DNS resolver (instead of the system's stub resolver) will be used. If set to "off", disables caching of DNS responses and, as side effect, DNS failover. Default is "on". Settings can be changed also during runtime (switch from internal to system resolver and back).


Alias name: dns_use_failover

use_dns_failover = on | off (default off)

If on and sending a request fails (due to not being allowed from an onsend_route, send failure, blocklisted destination or, when using tm, invite timeout), and the destination resolves to multiple ip addresses and/or multiple SRV records, the send will be re-tried using the next ip/record. In tm case, a new branch will be created for each new send attempt.

TCP Parameters

The following parameters allows to tweak the TCP behaviour.


Global parameter to disable TCP support in the SIP server. Default value is no.

Example of usage:



If a message received over a tcp connection has "alias" in its via a new tcp alias port will be created for the connection the message came from (the alias port will be set to the via one).

Based on draft-ietf-sip-connect-reuse-00.txt, but using only the port (host aliases are dangerous, involve extra DNS lookups and the need for them is questionable)

See force_tcp_alias for more details.

Note: For NAT traversal of TCP clients it is better to not use tcp_accept_aliases but just use nathelper module and fix_nated_[contact|register]() functions.

Default is no (off)

    tcp_accept_aliases= yes|no


Enable the internal TCP stack to expect a PROXY-protocol-formatted header as the first message of the connection. Both the human-readable (v1) and binary-encoded (v2) variants of the protocol are supported. This option is typically useful if you are behind a TCP load-balancer, such as HAProxy or an AWS' ELB, and allows the load-balancer to provide connection information regarding the upstream client. This enables the use of IP-based ACLs, even behind a load-balancer.

Please note that enabling this option will reject any inbound TCP connection that does not conform to the PROXY-protocol spec.

For reference - the PROXY protocol:

Default value is no.



Enable internal TCP receiving stack to accept HEP3 packets. This option has to be set to yes on a Kamailio instance acting as Homer SIPCapture server that is supposed to receive HEP3 packets over TCP/TLS.

Default value is no.



Control whether to throw or not error when there is no Content-Length header for requests received over TCP. It is required to be set to yes for XCAP traffic sent over HTTP/1.1 which does not use Content-Length header, but splits large bodies in many chunks. The module sanity can be used then to restrict this permission to HTTP traffic only, testing in route block in order to stay RFC3261 compliant about this mandatory header for SIP requests over TCP.

Default value is no.



If set to 1, reject duplicate connections coming from same source IP and port.

Default set to 0.

tcp_accept_unique = 1


Alias name: tcp_buf_write

If enabled, all the tcp writes that would block / wait for connect to finish, will be queued and attempted latter (see also tcp_conn_wq_max and tcp_wq_max).

Note: It also applies for TLS.

    tcp_async = yes | no (default yes)


Number of children processes to be created for reading from TCP connections. If no value is explicitly set, the same number of TCP children as UDP children (see "children" parameter) will be used.

Example of usage:



Control if the received buffer should be cloned from the TCP stream, needed by functions working inside the SIP message buffer (such as msg_apply_changes()).

Default is 0 (don't clone), set it to 1 for cloning.

Example of usage:



Lifetime in seconds for TCP sessions. TCP sessions which are inactive for longer than tcp_connection_lifetime will be closed by Kamailio. Default value is defined is 120. Setting this value to 0 will close the TCP connection pretty quick.

Note: As many SIP clients are behind NAT/Firewalls, the SIP proxy should not close the TCP connection as it is not capable of opening a new one.

Example of usage:



If set to 1, try to be more strict in matching outbound TCP connections, attempting to lookup first the connection using also local port, not only the local IP and remote IP+port.

Default is 0.



Time in seconds before an ongoing attempt to establish a new TCP connection will be aborted. Lower this value for faster detection of TCP connection problems. The default value is 10s.

Example of usage:



Maximum bytes queued for write allowed per connection. Attempting to queue more bytes would result in an error and in the connection being closed (too slow). If tcp_buf_write is not enabled, it has no effect.

    tcp_conn_wq_max = bytes (default 32 K)


Enable SIP outbound TCP keep-alive using PING-PONG (CRLFCRLF - CRLF).

    tcp_crlf_ping = yes | no default: yes


Tcp accepts will be delayed until some data is received (improves performance on proxies with lots of opened tcp connections). See linux tcp(7) TCP_DEFER_ACCEPT or freebsd ACCF_DATA(0). For now linux and freebsd only.

WARNING: the linux TCP_DEFER_ACCEPT is buggy (<=2.6.23) and doesn't work exactly as expected (if no data is received it will retransmit syn acks for ~ 190 s, irrespective of the set timeout and then it will silently drop the connection without sending a RST or FIN). Try to use it together with tcp_syncnt (this way the number of retrans. SYNACKs can be limited => the timeout can be controlled in some way).

On FreeBSD:

    tcp_defer_accept =  yes | no (default no)

On Linux:

    tcp_defer_accept =  number of seconds before timeout (default disabled)


Initial ACK for opened connections will be delayed and sent with the first data segment (see linux tcp(7) TCP_QUICKACK). For now linux only.

    tcp_delayed_ack  = yes | no (default yes when supported)


If enabled FDs used for sending will be cached inside the process calling tcp_send (performance increase for sending over tcp at the cost of slightly slower connection closing and extra FDs kept open)

    tcp_fd_cache = yes | no (default yes)


Enables keepalive for tcp (sets SO_KEEPALIVE socket option)

    tcp_keepalive = yes | no (default yes)


Number of keepalives sent before dropping the connection (TCP_KEEPCNT socket option). Linux only.

    tcp_keepcnt = number (not set by default)


Time before starting to send keepalives, if the connection is idle (TCP_KEEPIDLE socket option). Linux only.

    tcp_keepidle  = seconds (not set by default)


Time interval between keepalive probes, when the previous probe failed (TCP_KEEPINTVL socket option). Linux only.

    tcp_keepintvl = seconds (not set by default)


Lifetime of orphaned sockets in FIN_WAIT2 state (overrides tcp_fin_timeout on, see linux tcp(7) TCP_LINGER2). Linux only.

    tcp_linger2 = seconds (not set by default)


Maximum number of tcp connections (if the number is exceeded no new tcp connections will be accepted). Default is defined in tcp_init.h: #define DEFAULT_TCP_MAX_CONNECTIONS 2048

Example of usage:



Stop outgoing TCP connects (also stops TLS) by setting tcp_no_connect to yes.

You can do this any time, even even if Kamailio is already started (in this case using the command "kamcmd cfg.set_now_int tcp no_connect 1").


Poll method used (by default the best one for the current OS is selected). For available types see io_wait.c and poll_types.h: none, poll, epoll_lt, epoll_et, sigio_rt, select, kqueue, /dev/poll

Example of usage:



Buffer size used for tcp reads. A high buffer size increases performance on server with few connections and lot of traffic on them, but also increases memory consumption (so for lots of connection is better to use a low value). Note also that this value limits the maximum message size (SIP, HTTP) that can be received over tcp.

The value is internally limited to 16MByte, for higher values recompile Kamailio with higher limit in tcp_options.c (search for "rd_buf_size" and 16777216). Further, you may need to increase the private memory, and if you process the message stateful you may also have to increase the shared memory.

Default: 4096, can be changed at runtime.



Allows reuse of TCP ports. This means, for example, that the same TCP ports on which Kamailio is listening on, can be used as source ports of new TCP connections when acting as an UAC. Kamailio must have been compiled in a system implementing SO_REUSEPORT (Linux > 3.9.0, FreeBSD, OpenBSD, NetBSD, MacOSX). This parameter takes effect only if also the system on which Kamailio is running on supports SO_REUSEPORT.

    tcp_reuse_port = yes (default no)


Specify if connection should be closed (set to CONN_ERROR) if processing the received message results in error (that can also be due to negative return code from a configuration script main route block). If set to 1, the processing continues with the connection open.

Default 0 (close connection)

    tcp_script_mode = 1


Time in seconds after a TCP connection will be closed if it is not available for writing in this interval (and Kamailio wants to send something on it). Lower this value for faster detection of broken TCP connections. The default value is 10s.

Example of usage:


tcp_source_ipv4, tcp_source_ipv6

Set the source IP for all outbound TCP connections. If setting of the IP fails, the TCP connection will use the default IP address.

    tcp_source_ipv4 = IPv4 address
    tcp_source_ipv6 = IPv6 address


Number of SYN retransmissions before aborting a connect attempt (see linux tcp(7) TCP_SYNCNT). Linux only.

    tcp_syncnt = number of syn retr. (default not set)


Specify how long to wait (in milliseconds) to wait for data on tcp connections in certain cases. Now applies when reading on tcp connection for haproxy protocol.

Default: 5000ms (5secs)

tcp_wait_data = 10000


Block size used for tcp async writes. It should be big enough to hold a few datagrams. If it's smaller than a datagram (in fact a tcp write()) size, it will be rounded up. It has no influenced on the number of datagrams queued (for that see tcp_conn_wq_max or tcp_wq_max). It has mostly debugging and testing value (can be ignored).

Default: 2100 (~ 2 INVITEs), can be changed at runtime.


Maximum bytes queued for write allowed globally. It has no effect if tcp_buf_write is not enabled.

    tcp_wq_max = bytes (default 10 Mb)

TLS Parameters

Most of TLS layer attributes can be configured via TLS module parameters.


The port the SIP server listens to for TLS connections.

Default value is 5061.

Example of usage:



Maximum number of ls connections (if the number is exceeded no new ls connections will be accepted). It cannot exceed tcp_max_connections.

Default value is 2048.

Example of usage:


SCTP Parameters


Global parameter to disable SCTP support in the SIP server. See also enable_sctp.

Default value is auto.

Example of usage:



    enable_sctp = 0/1/2  - SCTP disabled (0)/ SCTP enabled (1)/auto (2), 
                           default auto (2)


sctp children no (similar to udp children)

    sctp_children = number 


Size for the sctp socket receive buffer

Alias name: sctp_socket_receive_buffer

    sctp_socket_rcvbuf = number 


Size for the sctp socket send buffer

Alias name: sctp_socket_send_buffer

    sctp_socket_sndbuf = number


Number of seconds before autoclosing an idle association (default: 180 s). Can be changed at runtime, but it will affect only new associations. E.g.:

    $ kamcmd cfg.seti sctp autoclose 120
    sctp_autoclose = seconds


Number of milliseconds before an unsent message/chunk is dropped (default: 32000 ms or 32 s). Can be changed at runtime, e.g.:

    $ kamcmd cfg.seti sctp send_ttl 180000
    sctp_send_ttl = milliseconds - n


How many times to attempt re-sending a message on a re-opened association, if the sctp stack did give up sending it (it's not related to sctp protocol level retransmission). Useful to improve reliability with peers that reboot/restart or fail over to another machine.

WARNING: use with care and low values (e.g. 1-3) to avoid "multiplying" traffic to unresponding hosts (default: 0). Can be changed at runtime.

    sctp_send_retries = 1


Controls whether or not sctp associations are tracked inside Kamailio. Turning it off would result in less memory being used and slightly better performance, but it will also disable some other features that depend on it (e.g. sctp_assoc_reuse). Default: yes.

Can be changed at runtime ("kamcmd sctp assoc_tracking 0"), but changes will be allowed only if all the other features that depend on it are turned off (for example it can be turned off only if first sctp_assoc_reuse was turned off).

Note: turning sctp_assoc_tracking on/off will delete all the tracking information for all the currently tracked associations and might introduce a small temporary delay in the sctp processing if lots of associations were tracked.

Config options depending on sctp_assoc_tracking being on: sctp_assoc_reuse.

    sctp_assoc_tracking = yes/no


Controls sctp association reuse. For now only association reuse for replies is affected by it. Default: yes. Depends on sctp_assoc_tracking being on.

Note that even if turned off, if the port in via corresponds to the source port of the association the request was sent on or if rport is turned on (force_rport() or via containing a rport option), the association will be automatically reused by the sctp stack. Can be changed at runtime (sctp assoc_reuse), but it can be turned on only if sctp_assoc_tracking is on.

    sctp_assoc_reuse = yes/no


Maximum number of allowed open sctp associations. -1 means maximum allowed by the OS. Default: -1. Can be changed at runtime (e.g.: kamcmd cfg.seti sctp max_assocs 10). When the maximum associations number is exceeded and a new associations is opened by a remote host, the association will be immediately closed. However it is possible that some SIP packets get through (especially if they are sent early, as part of the 4-way handshake).

When Kamailio tries to open a new association and the max_assocs is exceeded the exact behaviour depends on whether or not sctp_assoc_tracking is on. If on, the send triggering the active open will gracefully fail, before actually opening the new association and no packet will be sent. However if sctp_assoc_tracking is off, the association will first be opened and then immediately closed. In general this means that the initial sip packet will be sent (as part of the 4-way handshake).

    sctp_max_assocs = number


Initial value of the retr. timeout, used in RTO calculations (default: OS specific).

Can be changed at runtime (sctp srto_initial) but it will affect only new associations.

    sctp_srto_initial = milliseconds


Maximum value of the retransmission timeout (RTO) (default: OS specific).

WARNING: values lower than the sctp sack_delay will cause lots of retransmissions and connection instability (see sctp_srto_min for more details).

Can be changed at runtime (sctp srto_max) but it will affect only new associations.

    sctp_srto_max = milliseconds


Minimum value of the retransmission timeout (RTO) (default: OS specific).

WARNING: values lower than the sctp sack_delay of any peer might cause retransmissions and possible interoperability problems. According to the standard the sack_delay should be between 200 and 500 ms, so avoid trying values lower than 500 ms unless you control all the possible sctp peers and you do make sure their sack_delay is higher or their sack_freq is 1.

Can be changed at runtime (sctp srto_min) but it will affect only new associations.

    sctp_srto_min = milliseconds


Maximum retransmissions attempts per association (default: OS specific). It should be set to sctp_pathmaxrxt * no. of expected paths.

Can be changed at runtime (sctp asocmaxrxt) but it will affect only new associations.

    sctp_asocmaxrxt   = number


Maximum INIT retransmission attempts (default: OS specific).

Can be changed at runtime (sctp init_max_attempts).

    sctp_init_max_attempts = number


Maximum INIT retransmission timeout (RTO max for INIT). Default: OS specific.

Can be changed at runtime (sctp init_max_timeo).

    sctp_init_max_timeo = milliseconds


sctp heartbeat interval. Setting it to -1 will disable the heartbeats. Default: OS specific.

Can be changed at runtime (sctp hbinterval) but it will affect only new associations.

    sctp_hbinterval = milliseconds


Maximum retransmission attempts per path (see also sctp_asocmaxrxt). Default: OS specific.

Can be changed at runtime (sctp pathmaxrxt) but it will affect only new associations.

    sctp_pathmaxrxt = number


Delay until an ACK is generated after receiving a packet. Default: OS specific.

WARNING: a value higher than srto_min can cause a lot of retransmissions (and strange problems). A value higher than srto_max will result in very high connections instability. According to the standard the sack_delay value should be between 200 and 500 ms.

Can be changed at runtime (sctp sack_delay) but it will affect only new associations.

    sctp_sack_delay = milliseconds


Number of packets received before an ACK is sent (without waiting for the sack_delay to expire). Default: OS specific.

Note: on linux with lksctp up to and including 1.0.9 is not possible to set this value (having it in the config will produce a warning on startup).

Can be changed at runtime (sctp sack_freq) but it will affect only new associations.

    sctp_sack_freq = number


Maximum burst of packets that can be emitted by an association. Default: OS specific.

Can be changed at runtime (sctp max_burst) but it will affect only new associations.

    sctp_max_burst = number

UDP Parameters


Enables raw socket support for sending UDP IPv4 datagrams (40-50% performance increase on linux multi-cpu).

Possible values: 0 - disabled (default), 1 - enabled, -1 auto.

In "auto" mode it will be enabled if possible (sr started as root or with CAP_NET_RAW). udp4_raw can be used on Linux and FreeBSD. For other BSDs and Darwin one must compile with -DUSE_RAW_SOCKS. On Linux one should also set udp4_raw_mtu if the MTU on any network interface that could be used for sending is smaller than 1500.

The parameter can be set at runtime as long as sr was started with enough privileges (core.udp4_raw).

    udp4_raw = on


MTU value used for UDP IPv4 packets when udp4_raw is enabled. It should be set to the minimum MTU of all the network interfaces that could be used for sending. The default value is 1500. Note that on BSDs it does not need to be set (if set it will be ignored, the proper MTU will be used automatically by the kernel). On Linux it should be set.

The parameter can be set at runtime (core.udp4_raw_mtu). `


TTL value used for UDP IPv4 packets when udp4_raw is enabled. By default it is set to auto mode (-1), meaning that the same TTL will be used as for normal UDP sockets.

The parameter can be set at runtime (core.udp4_raw_ttl).

Blocklist Parameters


Alias name: dst_blocklist_ttl

How much time a blocklisted destination will be kept in the blocklist (w/o any update).

    dst_blocklist_expire = time in s (default 60 s)


How often the garbage collection will run (eliminating old, expired entries).

    dst_blocklist_gc_interval = time in s (default 60 s)


If off, the blocklist is not initialized at startup and cannot be enabled at runtime, this saves some memory.

    dst_blocklist_init = on | off (default on)


Maximum shared memory amount used for keeping the blocklisted destinations.

    dst_blocklist_mem = size in Kb (default 250 Kb)


Enable the destination blocklist: Each failed send attempt will cause the destination to be added to the blocklist. Before any send, this blocklist will be checked and if a match is found, the send is no longer attempted (an error is returned immediately).

Note: using the blocklist incurs a small performance penalty.

See also doc/dst_blocklist.txt.

    use_dst_blocklist = on | off (default off)

Real-Time Parameters


Sets real time priority for all the Kamailio processes, or the timers (bitmask).

   Possible values:   0  - off
                      1  - the "fast" timer
                      2  - the "slow" timer
                      4  - all processes, except the timers

Example: real_time= 7 => everything switched to real time priority.

    real_time = <int> (flags) (default off)


Real time scheduling policy, 0 = SCHED_OTHER, 1= SCHED_RR and 2=SCHED_FIFO

    rt_policy= <0..3> (default 0)


Real time priority used for everything except the timers, if real_time is enabled.

    rt_prio = <int> (default 0)


Alias name: rt_ftimer_policy

Like rt_policy but for the "fast" timer.

    rt_timer1_policy=<0..3> (default 0)


Alias name: rt_fast_timer_prio, rt_ftimer_prio

Like rt_prio but for the "fast" timer process (if real_time & 1).

    rt_timer1_prio=<int> (default 0)


Alias name: rt_stimer_policy

Like rt_policy but for the "slow" timer.

    rt_timer2_policy=<0..3> (default 0)


Alias name: rt_stimer_prio

Like rt_prio but for the "slow" timer.

    rt_timer2_prio=<int> (default 0)

Core Functions

Functions exported by core that can be used in route blocks.


Add rport parameter to local generated Via header -- see RFC3581. In effect for forwarded SIP requests.

Example of usage:




'break' statement can be used to end a 'case' block in a 'switch' statement or exit from a 'while' statement.


Stop the execution of the configuration script and alter the implicit action which is done afterwards.

If the function is called in a 'branch_route' then the branch is discarded (implicit action for 'branch_route' is to forward the request).

If the function is called in the default 'onreply_route' then you can drop any response. If the function is called in a named 'onreply_route' (transaction stateful) then any provisional reply is discarded. (Implicit action for 'onreply_route' is to send the reply upstream according to Via header.)

Example of usage:

    onreply_route {
        if(status=="200") {
            drop(); # this works

    onreply_route[FOOBAR] {
        if(status=="200") {
            drop(); # this is ignored


Stop the execution of the configuration script -- it has the same behaviour as return(0). It does not affect the implicit action to be taken after script execution.

    request_route {
      if (route(ABC)) {
        xlog("L_NOTICE","method $rm is INVITE\n");
      } else {
        xlog("L_NOTICE","method is $rm\n");

    route[ABC] {
      if (is_method("INVITE")) {
      } else if (is_method("REGISTER")) {
      } else if (is_method("MESSAGE")) {
        sl_send_reply("403","IM not allowed");


error("p1", "p2");

Not properly implemented yet - prints a log messages with the two string parameters.


Basic implementation of executing an external application with C system() function. Look also at the functions exported by exec module.



The force_rport() adds the rport parameter to the first Via header of the received message. Thus, Kamailio will add the received port to the top most Via header in the SIP message, even if the client does not indicate support for rport. This enables subsequent SIP messages to return to the proper port later on in a SIP transaction.

This is useful for NAT traversal, to enforce symmetric response signaling.

The rport parameter is defined in RFC 3581.

Note: there is also a force_rport parameter which changes the global behavior of the SIP proxy.

Example of usage:



Alias for force_rport();


Force to send the message from the specified socket (it must be one of the sockets specified with the listen directive). If the protocol doesn't match (e.g. UDP message "forced" to a TCP socket) the closest socket of the same protocol is used.

This function does not support pseudo-variables, use the set_send_socket() function from the corex module instead.

Example of usage:



Alias name: add_tcp_alias


adds a tcp port alias for the current connection (if tcp). Useful if you want to send all the traffic to port_alias through the same connection this request came from (it could help for firewall or nat traversal). With no parameters adds the port from the message via as the alias. When the "aliased" connection is closed (e.g. it's idle for too much time), all the port aliases are removed.


Forward in stateless mode the SIP request to destination address set in $du or $ru.

Example of usage:

    $du = "sip:;transport=tcp";



Test if a flag is set for current processed message (if the flag value is 1). The value of the parameter can be in range of 0..31.

For more see: - Kamailio - Flag Operations

Example of usage:

      if(isflagset(3)) {
          log("flag 3 is set\n");

Kamailio also supports named flags. They have to be declared at the beginning of the config file with:

 flags  flag1_name[:position],  flag2_name ...


    flags test, a:1, b:2 ;
    request_route {
        if (isflagset(a)){ # equiv. to isflagset(1)
        resetflag(b);  # equiv. to resetflag(2)


Checks if a pseudo variable argument contains integer value.

    if(is_int("$avp(foobar)")) {
      log("foobar contains an integer\n");


Write text message to standard error terminal or syslog. You can specify the log level (the integer id) as first parameter.

The parameters are static values. If you want dynamic parameters with variables, look at xlog module.

For more see:

Example of usage:

      log("just some text message\n");
      log(1, "another text message\n");


Add the string parameter in front of username in R-URI.

Example of usage:





The return() function allows you to return any integer value from a called route() block. You can test the value returned by a route using $retcode variable (which is same as $rc or $?).

return(0) is same as exit();

In logical evaluation expressions:

  • Negative is FALSE
  • Positive is TRUE

If no value is specified, or a route reaches its end without executing a return statement, it returns 1. If return is used in the top level route is equivalent with exit [val].

Example usage:

    request_route {
      if (route(RET)) {
        xlog("L_NOTICE","method $rm is INVITE\n");
      } else {
        xlog("L_NOTICE","method $rm is REGISTER\n");

    route[RET] {
      if (is_method("INVITE")) {
      } else if (is_method("REGISTER")) {
      } else {

IMPORTANT: do not compare route block or module function execution in a condition with the value of the return code. Next example is showing a wrong use:

    request_route {
      if (route(RET) == -2) {
        xinfo("return is -2\n");
      } else {
        xinfo("return is not -2\n"); ### THIS IS GOING TO BE EXECUTED

    route[RET] {
      return -2;

See also the FAQ for how the function return code is evaluated:

Note: starting with version 5.7.0-dev, this behaviour can be changed with return_mode global parameter.


Control the return code evaluation mode:

  • 0 (default) - evaluation is like so far (negative is false, positive is true)
  • 1 - propagate return value and evaluation has to be done with >0 or <0, otherwise value!=0 is evaluated to true no matter is negative or positive


Set the R-URI to the value of the R-URI as it was when the request was received by server (undo all changes of R-URI).

Example of usage:



Alias name: sethostport, sethp

Rewrite the domain part and port of the R-URI with the value of function's parameter. Other parts of the R-URI like username and URI parameters remain unchanged.

Example of usage:



Alias name: sethostporttrans, sethpt

Rewrite the domain part and port of the R-URI with the value of function's parameter. Also allows to specify the transport parameter. Other parts of the R-URI like username and URI parameters remain unchanged.

Example of usage:



Alias name: sethost, seth

Rewrite the domain part of the R-URI with the value of function's parameter. Other parts of the R-URI like username, port and URI parameters remain unchanged.

Example of usage:



Alias name: setport, setp

Rewrites/sets the port part of the R-URI with the value of function's parameter.

Example of usage:



Alias name: seturi

Rewrite the request URI.

Example of usage:



Alias name: setuserpass, setup

Rewrite the password part of the R-URI with the value of function's parameter.

Example of usage:



Alias name: setuser, setu

Rewrite the user part of the R-URI with the value of function's parameter.

Example of usage:



Execute route block given in parameter. Parameter may be name of the block or a string valued expression.

Examples of usage:

  route(@received.proto + "_proto_" + $var(route_set));


Select a value based on conditional expression.


selval(evalexpr, valexp1, valexpr2)

This is a core statement that return the 2nd parameter if the 1st parameter is evaluated to true, or 3rd parameter if the 1st parameter is evaluated to false. It can be considered a core function that is equivalent of ternary condition/operator


$var(x) = selval($Ts mod 2, "true/" + $ru, "false/" + $rd);

The first parameter is a conditional expression, like those used for IF, the 2nd and 3rd parameters can be expressions like those used in the right side of assignments.


Same as advertised_address but it affects only the current message. It has priority if advertised_address is also set.

Example of usage:



Same as advertised_port but it affects only the current message. It has priority over advertised_port.

Example of usage:



The message will be forwarded only if there is already an existing connection to the destination. It applies only to connection oriented protocols like TCP and TLS (TODO: SCTP), for UDP it will be ignored. The behavior depends in which route block the function is called:

  • normal request route: affects stateless forwards and tm. For tm it affects all the branches and the possible retransmissions (in fact there are no retransmission for TCP/TLS).
  • onreply_route[0] (stateless): equivalent to set_reply_*() (it's better to use set_reply_* though)
  • onreply_route[!=0] (tm): ignored
  • branch_route: affects the current branch only (all messages sent on this branch, like possible retransmissions and CANCELs).
  • onsend_route: like branch route

Example of usage:

  route {
    if (lookup()) {
      //requests to local users. They are usually behind NAT so it does not make sense to try
      //to establish a new TCP connection 


Try to close the connection (the one on which the message is sent out) after forwarding the current message. Can be used in same route blocks as set_forward_no_connect().

Note: Use with care as you might not receive the replies anymore as the connection is closed.


Like set_forward_no_connect(), but for replies to the current message (local generated replies and replies forwarded by tm). The behavior depends in which route block the function is called:

  • normal request route: affects all replies sent back on the transaction (either local or forwarded) and all local stateless replies (sl_reply()).
  • onreply_route: affects the current reply (so the send_flags set in the onreply_route will be used if the reply for which they were set is the winning final reply or it's a provisional reply that is forwarded)
  • branch_route: ignored.
  • onsend_route: ignored

Example of usage:

  route[4] {
    //requests from local users. There are usually behind NAT so it does not make sense to try
    //to establish a new TCP connection for the replies
    // do authentication and call routing


Like set_reply_no_connect, but closes the TCP connection after sending. Can be used in same route blocks as set_reply_no_connect.

Example of usage:

  route {
    if (...caller-is-not-registered...) {
      // reject unregistered client
      // if request was received via TCP/TLS close the connection, as
      // this may trigger re-registration of the client.
      sl_send_reply("403","REGISTER first");



Set a flag for current processed message. The value of the parameter can be in range of 0..31. The flags are used to mark the message for special processing (e.g., accounting) or to keep some state (e.g., message authenticated).

For more see: - Kamailio - Flag Operations

Example of usage:



Strip the first N-th characters from username of R-URI (N is the value of the parameter).

Example of usage:



Strip the last N-th characters from username of R-URI (N is the value of the parameter).

Example of usage:



  • proto - TCP|TLS|SCTP|UDP - like udp_mtu_try_proto global parameter but works on a per packet basis and not globally.




Add "user=phone" parameter to R-URI.

Custom Global Parameters

These are parameters that can be defined by the writer of kamailio.cfg in order to be used inside routing blocks. One of the important properties for custom global parameters is that their value can be changed at runtime via RPC commands, without restarting Kamailio.

The definition of a custom global parameter must follow the pattern:

group.variable = value desc "description"

The value can be a quoted string or integer number.


pstn.gw_ip = "" desc "PSTN GW Address"

The custom global parameter can be accessed inside a routing block via:



$ru = "sip:" + $rU + "@" + $sel(cfg_get.pstn.gw_ip);

Note: Some words cannot be used as (part of) names for custom variables or groups, and if they are used a syntax error is logged by kamailio. These keywords are: "yes", "true", "on", "enable", "no", "false", "off", "disable", "udp", "UDP", "tcp", "TCP", "tls", "TLS", "sctp", "SCTP", "ws", "WS", "wss", "WSS", "inet", "INET", "inet6", "INET6", "sslv23", "SSLv23", "SSLV23", "sslv2", "SSLv2", "SSLV2", "sslv3", "SSLv3", "SSLV3", "tlsv1", "TLSv1", "TLSV1"

Routing Blocks

The routing blocks are the parts of the configuration file executed by kamailio at runtime. They can be seen as blocks of actions similar to functions (or procedures) from common programming languages.

A routing block is identified by a specific token, followed by a name in between square brackets and actions in between curly braces.

route_block_id[NAME] {

The name can be any alphanumeric string, with specific routing blocks enforcing a particular format.

🔥IMPORTANT: Note: route(number) is equivalent to route("number").

Route blocks can be executed on network events (e.g., receiving a SIP message), timer events (e.g., retransmission timeout) or particular events specific to modules.

There can be so called sub-route blocks, which can be invoked from another route blocks, like a function. Invocation is done with route followed by the name of sub-route to execute, enclosed in between parentheses.





Request routing block - is executed for each SIP request.

It contains a set of actions to be executed for SIP requests received from the network. It is the equivalent of main() function for handling the SIP requests.

🔥IMPORTANT: For backward compatibility reasons, the main request route block can be identified by route{...} or route[0]{...}'.

The implicit action after execution of the main route block is to drop the SIP request. To send a reply or forward the request, explicit actions (e.g., sl_send_reply(), forward(), t_relay()) must be called inside the route block.

Example of usage:

    request_route {
         if(is_method("OPTIONS")) {
            # send reply for each options request
            sl_send_reply("200", "ok");
    route[FWD] {
         # forward according to uri


This block is used to define 'sub-routes' - group of actions that can be executed from another routing block. Originally targeted as being executed from 'request_route', it can be executed now from all the other blocks. Be sure you put there the actions valid for the root routing block executing the sub-route.

The definition of the sub-route block follows the general rules, with a name in between square brackets and actions between curly braces. A sub-route can return an integer value back to the routing block that executed it. The return code can be retrieved via $rc variables.

Evaluation of the return of a subroute is done with following rules:

  • negative value is evaluated as false
  • 0 - is interpreted as exit
  • positive value is evaluated as true
request_route {
  if(route(POSITIVE)) {
    xlog("return number is positive\n");
  if( ! route(NEGATIVE)) {
    xlog("return number is negative\n");
  if( route(ZERO)) {
    xlog("this log message does not appear\n");

route[POSITIVE] {
  return 10;

route[NEGATIVE] {
  return -8;

route[ZERO] {
  return 0;

A sub-route can execute another sub-route. There is a limit to the number of recursive levels, avoiding ending up in infinite loops -- see max_recursive_level global parameter.

The sub-route blocks allow to make the configuration file modular, simplifying the logic and helping to avoid duplication of actions.


Request's branch routing block. It contains a set of actions to be taken for each branch of a SIP request. It is executed only by TM module after it was armed via t_on_branch("branch_route_index").

Example of usage:

    request_route {
        if(!t_relay()) {
            sl_send_reply("500", "relaying failed");
    branch_route[OUT] {
        if(uri=~"10\.10\.10\.10") {
            # discard branches that go to


Failed transaction routing block. It contains a set of actions to be taken each transaction that received only negative replies (>=300) for all branches. The failure_route is executed only by TM module after it was armed via t_on_failure("failure_route_index").

Note that in failure_route is processed the request that initiated the transaction, not the reply .

Example of usage:

    request_route {
        if(!t_relay()) {
            sl_send_reply("500", "relaying failed");
    failure_route[TOVOICEMAIL] {
        if(is_method("INVITE")) {
             # call failed - relay to voice mail


Main SIP response (reply) handling block - it contains a set of actions to be executed for SIP replies. It is executed for all replies received from the network.

It does not have a name and it is executed by the core, before any other module handling the SIP reply. It is triggered only by SIP replies received on the network.

There is no network route that can be enforced for a SIP reply - it is sent based on Via header, according to SIP RFC3261 - therefore no dedicated actions for forwarding the reply must be used in this block.

This routing block is optional, if missing, the SIP reply is sent to the address in 2nd Via header.

One can decide to drop a SIP reply by using drop action.


reply_route {
  if(status=="128") {

🔥IMPORTANT: Note: for backward compatibility reasons, the main reply routing block can be also identified by onreply_route {...} or onreply_route[0] {...}.


SIP reply routing block executed by tm module. It contains a set of actions to be taken for SIP replies in the context of an active transaction.

The onreply_route must be armed for the SIP requests whose replies should be processed within it, via t_on_reply("onreply_route_index").

Core 'reply_route' block is executed before a possible tm 'onreply_route' block.

  request_route {
      if(!t_relay()) {
          sl_send_reply("500", "relaying failed");

  reply_route {
      if(!t_check_trans()) {

  onreply_route[LOGRPL] {
      if(status=~"1[0-9][0-9]") {
           log("provisional response\n");


The route is executed in when a SIP request is sent out. Only a limited number of commands are allowed (drop, if + all the checks, msg flag manipulations, send(), log(), textops::search()).

In this route the final destination of the message is available and can be checked (with snd_ip, snd_port, to_ip, to_port, snd_proto, snd_af).

This route is executed only when forwarding requests - it is not executed for replies, retransmissions, or locally generated messages (e.g. via fifo uac).


  onsend_route {
    if(to_ip== && !isflagset(12)){
      log(1, "message blocked\n");
  • snd_ip, snd_port - behave like src_ip/src_port, but contain the ip/port Kamailio will use to send the message
  • to_ip, to_port - like above, but contain the ip/port the message will be sent to (not to be confused with dst_ip/dst_port, which are the destination of the original received request: Kamailio's ip and port on which the message was received)
  • snd_proto, snd_af - behave like proto/af but contain the protocol/address family that Kamailio will use to send the message
  • msg:len - when used in an onsend_route, msg:len will contain the length of the message on the wire (after all the changes in the script are applied, Vias are added a.s.o) and not the lentgh of the original message.


Generic type of route executed when specific events happen.

Prototype: event_route[groupid:eventid]

  • groupid - should be the name of the module that triggers the event
  • eventid - some meaningful short text describing the event

Core Event Routes


  • event_route[core:worker-one-init] - executed by core after the first udp sip worker process executed the child_init() for all modules, before starting to process sip traffic
    • note that due to forking, other sip workers can get faster to listening for sip traffic
event_route[core:worker-one-init] {
        xlog("L_INFO","Hello world\n");
  • event_route[core:msg-received] - executed when a message is received from the network. It runs with a faked request and makes available the $rcv(key) variables to access what was received and related attribtues.
    • it has to be enabled with received_route_mode global parameter. For usage via Kemi, set kemi.received_route_callback global parameter.
    • if drop is executed, the received message is no longer processed
event_route[core:msg-received] {
  xlog("rcv on $rcv(af)/$rcv(proto): ($rcv(len)) [$rcv(buf)] from [$rcv(srcip):$rcv(srcport)] to [$rcv(rcvip):$rcv(rcvport)]\n");
  if($rcv(srcip) == "") {
  • event_route[core:pre-routing] - executed by core on receiving SIP traffic before running request_route or reply_route.
    • if drop is used, then the message is not processed further with request_route or reply_route in the same process. This can be useful together with sworker module which can delegate the processing to another worker.
event_route[core:pre-routing] {
    xinfo("pre-routing rules\n");
    if(is_method("REGISTER")) {
        # delegate processing of REGISTERs to a special group of workers
        if(sworker_task("reg")) {
  • event_route[core:receive-parse-error] - executed by core on receiving a broken SIP message that can not be parsed.
    • note that the SIP message is broken in this case, but it gets access to source and local socket addresses (ip, port, proto, af) as well as the whole message buffer and its size
event_route[core:receive-parse-error] {
        xlog("got a parsing error from $si:$sp, message $mb\n");

Module Event Routes

Here are only a few examples, to see if a module exports event_route blocks and when they are executed, check the readme of the module.

  • event_route[htable:mod-init] - executed by htable module after all modules have been initialised. Good for initialising values in hash tables.
modparam("htable", "htable", "a=>size=4;")

event_route[htable:mod-init] {
  $sht(a=>calls-to:: = 0;
  $sht(a=>max-calls-to:: = 100;

request_route {
  if(is_method("INVITE") && !has_totag())
    switch($rd) {
      case "":
        $sht(a=>calls-to:: =
            $sht(a=>calls-to:: + 1;
           sl_send_reply("500", "To many calls to .10");
  • event_route[tm:local-request] - executed on locally generated requests.
event_route [tm:local-request] { # Handle locally generated requests
  xlog("L_INFO", "Routing locally generated $rm to <$ru>\n");
  t_set_fr(10000, 10000);
  • event_route[tm:branch-failure] - executed on all failure responses.
request_route {

event_route[tm:branch-failure:myroute] {
  xlog("L_INFO", "Handling $T_reply_code response to $rm to <$ru>\n");
  if (t_check_status("430")) { # Outbound flow failed
    unregister("location", "$tu", "$T_reply_ruid");
    if (t_next_contact_flow()) {

Script Statements


IF-ELSE statement


    if(expr) {
    } else {

The expr should be a valid logical expression.

The logical operators that can be used in expr:

  • ==: equal
  • !=: not equal
  • =~: case-insensitive regular expression matching: Note: Posix regular expressions will be used, e.g. use [[:digit:]]{3} instead of \d\d\d
  • !~: regular expression not-matching (NOT PORTED from Kamailio 1.x, use !(x =~ y))
  • >: greater
  • >=: greater or equal
  • <: less
  • <=: less or equal
  • &&: logical AND
  • ||: logical OR
  • !: logical NOT

Example of usage:

      log("this sip message is an invite\n");
  } else {
      log("this sip message is not an invite\n");

See also the FAQ for how the function return code is evaluated:


SWITCH statement - it can be used to test the value of a pseudo-variable.

IMPORTANT NOTE: break can be used only to mark the end of a case branch (as it is in shell scripts). If you are trying to use break outside a case block the script will return error -- you must use return there.

Example of usage:

    route {
            case -1:
                log("process INVITE requests here\n");
            case 1:
                log("process REGISTER requests here\n");
            case 2:
            case 3:
                log("process SUBSCRIBE and NOTIFY requests here\n");
                log("process other requests here\n");

        # switch of R-URI username
            case "101":
                log("destination number is 101\n");
            case "102":
                log("destination number is 102\n");
            case "103":
            case "104":
                log("destination number is 103 or 104\n");
            # cases with starting slash are regular expressions
            case /"\+49.*":
                log("destination number is germany\n");
            case /"\+33.*":
                log("destination number is france\n");
                log("unknown destination number\n");


NOTE: take care while using return - return(0) stops the execution of the script.


while statement

Example of usage:

  $var(i) = 0;
  while($var(i) < 10)
      xlog("counter: $var(i)\n");
      $var(i) = $var(i) + 1;

Script Operations

Assignments together with string and arithmetic operations can be done directly in configuration file.


Assignments can be done like in C, via = (equal). The following pseudo-variables can be used in left side of an assignment:

  • Unordered List Item AVPs - to set the value of an AVP
  • script variables ($var(...)) - to set the value of a script variable
  • shared variables ($shv(...))
  • $ru - to set R-URI
  • $rd - to set domain part of R-URI
  • $rU - to set user part of R-URI
  • $rp - to set the port of R-URI
  • $du - to set dst URI
  • $fs - to set send socket
  • $br - to set branch
  • $mf - to set message flags value
  • $sf - to set script flags value
  • $bf - to set branch flags value

    $var(a) = 123;

For avp's there a way to remove all values and assign a single value in one statement (in other words, delete existing AVPs with same name, add a new one with the right side value). This replaces the := assignment operator from kamailio < 3.0.

$(avp(i:3)[*]) = 123;
$(avp(i:3)[*]) = $null;

String Operations

For strings, + is available to concatenate.

$var(a) = "test";
$var(b) = "sip:" + $var(a) + "@" + $fd;

Arithmetic Operations

For numbers, one can use:

  • + : plus
  • - : minus
  • / : divide
  • * : multiply
  • mod : modulo (SER uses % instead of mod)
  • | : bitwise OR
  • & : bitwise AND
  • ^ : bitwise XOR
  • ~ : bitwise NOT
  • << : bitwise left shift
  • >> : bitwise right shift


    $var(a) = 4 + ( 7 & ( ~2 ) );

NOTE: to ensure the priority of operands in expression evaluations do use parenthesis.

Arithmetic expressions can be used in condition expressions.

    if( $var(a) & 4 )
        log("var a has third bit set\n");


  1. type casts operators: (int), (str).
  2. string comparison: eq, ne
  3. integer comparison: ieq, ine

Note: The names are not yet final (use them at your own risk). Future version might use ==/!= only for ints (ieq/ine) and eq/ne for strings (under debate). They are almost equivalent to == or !=, but they force the conversion of their operands (eq to string and ieq to int), allowing among other things better type checking on startup and more optimizations.

Non equivalent examples:

0 == "" (true) is not equivalent to 0 eq "" (false: it evaluates to "0" eq "").

"a" ieq "b" (true: (int)"a" is 0 and (int)"b" is 0) is not equivalent to "a" == "b" (false).

Note: internally == and != are converted on startup to eq/ne/ieq/ine whenever possible (both operand types can be safely determined at start time and they are the same).

  1. Kamailio tries to guess what the user wanted when operators that support multiple types are used on different typed operands. In general convert the right operand to the type of the left operand and then perform the operation. Exception: the left operand is undef. This applies to the following operators: +, == and !=.

    Special case: undef as left operand: For +: undef + expr -> undef is converted to string => "" + expr. For == and !=: undef == expr -> undef is converted to type_of expr. If expr is undef, then undef == undef is true (internally is converted to string).

  2. expression evaluation changes: Kamailio will auto-convert to integer or string in function of the operators:

     int(undef)==0,  int("")==0, int("123")==123, int("abc")==0
     str(undef)=="", str(123)=="123".
  3. script operators for dealing with empty/undefined variables

    defined expr - returns true if expr is defined, and false if not.
                   Note: only a standalone avp or pvar can be
                   undefined, everything else is defined.
    strlen(expr) - returns the lenght of expr evaluated as string.
    strempty(expr) - returns true if expr evaluates to the empty
                     string (equivalent to expr=="").
    Example: if (defined $v && !strempty($v)) $len=strlen($v);

Command Line Parameters

Kamailio can be started with a set of command line parameters, providing more flexibility to control what is doing at runtime. Some of them can be quite useful when running on containerised environments.

To see the the available command line parameters, run kamailio -h:

    # kamailio -h

version: kamailio 5.7.0-dev1 (x86_64/darwin) 353aa1
Usage: kamailio [options]
    -a mode      Auto aliases mode: enable with yes or on,
                  disable with no or off
    --alias=val  Add an alias, the value has to be '[proto:]hostname[:port]'
                  (like for 'alias' global parameter)
    --atexit=val Control atexit callbacks execution from external libraries
                  which may access destroyed shm memory causing crash on shutdown.
                  Can be y[es] or 1 to enable atexit callbacks, n[o] or 0 to disable,
                  default is yes.
    -A define    Add config pre-processor define (e.g., -A WITH_AUTH,
                  -A 'FLT_ACC=1', -A 'DEFVAL="str-val"')
    -b nr        Maximum OS UDP receive buffer size which will not be exceeded by
                  auto-probing-and-increase procedure even if OS allows
    -c           Check configuration file for syntax errors
    --cfg-print  Print configuration file evaluating includes and ifdefs
    -d           Debugging level control (multiple -d to increase the level from 0)
    --debug=val  Debugging level value
    -D           Control how daemonize is done:
         not fork (almost) anyway;
         not daemonize creator;
                  -DDD..daemonize (default)
    -e           Log messages printed in terminal colors (requires -E)
    -E           Log to stderr
    -f file      Configuration file (default: /tmp/kamailio-dev/etc/kamailio/kamailio.cfg)
    -g gid       Change gid (group id)
    -G file      Create a pgid file
    -h           This help message
    --help       Long option for `-h`
    -I           Print more internal compile flags and options
    -K           Turn on "via:" host checking when forwarding replies
    -l address   Listen on the specified address/interface (multiple -l
                  mean listening on more addresses). The address format is
                  where proto=udp|tcp|tls|sctp,
                  addr_lst= addr|(addr, addr_lst),
                  addr=host|ip_address|interface_name and
                  advaddr=addr[:port] (advertised address).
                  E.g: -l localhost, -l udp:, -l eth0:5062,
                  -l udp:,
                  -l "sctp:(eth0)", -l "(eth0, eth1,".
                  The default behaviour is to listen on all the interfaces.
    --loadmodule=name load the module specified by name
    --log-engine=log engine name and data
    -L path      Modules search path (default: /tmp/kamailio-dev/lib64/kamailio/modules)
    -m nr        Size of shared memory allocated in Megabytes
    --modparam=modname:paramname:type:value set the module parameter
                  type has to be 's' for string value and 'i' for int value,
    --all-errors Print details about all config errors that can be detected
    -M nr        Size of private memory allocated, in Megabytes
    -n processes Number of child processes to fork per interface
                  (default: 8)
    -N           Number of tcp child processes (default: equal to `-n')
    -O nr        Script optimization level (debugging option)
    -P file      Create a pid file
    -Q           Number of sctp child processes (default: equal to `-n')
    -r           Use dns to check if is necessary to add a "received="
                  field to a via
    -R           Same as `-r` but use reverse dns;
                  (to use both use `-rR`)
    --server-id=num set the value for server_id
    --subst=exp set a subst preprocessor directive
    --substdef=exp set a substdef preprocessor directive
    --substdefs=exp set a substdefs preprocessor directive
    -S           disable sctp
    -t dir       Chroot to "dir"
    -T           Disable tcp
    -u uid       Change uid (user id)
    -v           Version number
    --version    Long option for `-v`
    -V           Alternative for `-v`
    -x name      Specify internal manager for shared memory (shm)
                  - can be: fm, qm or tlsf
    -X name      Specify internal manager for private memory (pkg)
                  - if omitted, the one for shm is used
    -Y dir       Runtime dir path
    -w dir       Change the working directory to "dir" (default: "/")
    -W type      poll method (depending on support in OS, it can be: poll,
                  epoll_lt, epoll_et, sigio_rt, select, kqueue, /dev/poll)

Log Engine CLI Parameter

The --log-engine parameter allows to specify what logging engine to be used, which is practically about the format of the log messages. If not set at all, then Kamailio does the classic style of line-based plain text log messages.

The value of this parameter can be --log-engine=name or --log-engine=name:data.

The name of the log engine can be:

  • json - write logs in structured JSON format
    • the data for json log engine can be a set of character flags:
      • a - add log prefix as a special field
      • A - do not add log prefix
      • c - add Call-ID (when available) as a dedicated JSON attribute
      • j - the log prefix and message fields are printed in JSON structure format, detecting if they are enclosed in between { } or adding them as a text field
      • M - strip EOL (\n) from the value of the log message field
      • N - do not add EOL at the end of JSON document
      • p - the log prefix is printed as it is in the root json document, it has to start with comma (,) and be a valid set of json fields
      • U - CEE (Common Event Expression) schema format -

Example of JSON logs when running Kamailio with --log-engine=json:M :

    { "idx": 1, "pid": 18239, "level": "DEBUG", "module": "maxfwd", "file": "mf_funcs.c", "line": 74, "function": "is_maxfwd_present", "logprefix": "{1 1 OPTIONS 715678756@} ", "message": "value = 70 " }

    { "idx": 1, "pid": 18239, "level": "DEBUG", "module": "core", "file": "core/socket_info.c", "line": 644, "function": "grep_sock_info", "logprefix": "{1 1 OPTIONS 715678756@} ", "message": "checking if host==us: 9==9 && [] == []" }

Example config for printing log message with j flag:

    xinfo("{ \"src_ip\": \"$si\", \"method\": \"$rm\", \"text\": \"request received\" }");

Example config for printing log messages with p flag:

    log_prefix=", \"src_ip\": \"$si\", \"tv\": $TV(Sn), \"mt\": $mt, \"ua\": \"$(ua{s.escape.common})\", \"cseq\": \"$hdr(CSeq)\""