4.12.1.16 Internet address manipulation functions

Following functions operate on IPv4 addresses and CIDRs.

Built-in Function: number ntohl (number n)

Converts the number n, from host to network byte order. The argument n is treated as an unsigned 32-bit number.

Built-in Function: number htonl (number n)

Converts the number n, from network to host byte order. The argument n is treated as an unsigned 32-bit number.

Built-in Function: number ntohs (number n)

The argument n is treated as an unsigned 16-bit number. The function converts this number from network to host order.

Built-in Function: number htons (number n)

The argument n is treated as an unsigned 16-bit number. The function converts this number from host to network order.

Built-in Function: number inet_aton (string s)

Converts the Internet host address s from the standard numbers-and-dots notation into the equivalent integer in host byte order.

 
inet_aton("127.0.0.1") ⇒ 2130706433

The numeric data type in MFL is signed, therefore on machines with 32 bit integers, this conversion can result in a negative number:

 
inet_aton("255.255.255.255") ⇒ -1

However, this does not affect arithmetical operations on IP addresses.

Built-in Function: string inet_ntoa (number n)

Converts the Internet host address n, given in host byte order to string in standard numbers-and-dots notation:

 
inet_ntoa(2130706433) ⇒ "127.0.0.1"
Built-in Function: number len_to_netmask (number n)

Convert number of masked bits n to IPv4 netmask:

 
inet_ntoa(len_to_netmask(24)) ⇒ 255.255.255.0
inet_ntoa(len_to_netmask(7)) ⇒ 254.0.0.0

If n is greater than 32 the function raises e_range exception.

Built-in Function: number netmask_to_len (number mask)

Convert IPv4 netmask mask into netmask length (number of bits preserved by the mask):

 
netmask_to_len(inet_aton("255.255.255.0")) ⇒ 24
netmask_to_len(inet_aton("254.0.0.0")) ⇒ 7
Library Function: boolean match_cidr (string ip,   string cidr)

This function is defined in ‘match_cidr.mf’ module (see section Modules).

It returns true if the IP address ip pertains to the IP range cidr. The first argument, ip, is a string representation of an IP address. The second argument, cidr, is a string representation of a IP range in CIDR notation, i.e. "A.B.C.D/N", where A.B.C.D is an IPv4 address and N specifies the prefix length – the number of shared initial bits, counting from the left side of the address.

The following example will reject the mail if the IP address of the sending machine does not belong to the block 10.10.1.0/19:

 
if not match_cidr(${client_addr}, "10.10.1.0/19")
  reject
fi