lua-resty-iputils, in Openresty, the utility function for processing IP addresses

 

lua-resty-iputils

Collection utility function for processing the IP address.

Outline

Copy the code


init_by_lua_block {


 local iputils = require("resty.iputils")


 iputils.enable_lrucache()


 local whitelist_ips = {


"127.0.0.1",


"10.10.10.0/24",


"192.168.0.0/16",


 }



 -- WARNING: Global variable, recommend this is cached at the module level


 -- https://github.com/openresty/lua-nginx-module#data-sharing-within-an-nginx-worker


 whitelist = iputils.parse_cidrs(whitelist_ips)


}



access_by_lua_block {


 local iputils = require("resty.iputils")


 if not iputils.ip_in_cidrs(ngx.var.remote_addr, whitelist) then


 return ngx.exit(ngx.HTTP_FORBIDDEN)


 end


}


method

enable_lrucache

syntax: ok, err = iputils.enable_lrucache(size?)

LruCache object is used to create a global cache ip2bin lookup.

Size is optional, the default value 4000 (each worker thread ~ 1MB)

Repeatedly call will reset the cache

ip2bin

syntax: bin_ip, bin_octets = iputils.ip2bin(ip)

Return binary octets containing the IPv4 address of each binary representation of a table of FIG.

Returns an error message nil and error messages

parse_cidr

syntax: lower, upper = iputils.parse_cidr(cidr)

Returns the lowest IPv4 network (network) and the highest (broadcast) address binary representation.

parse_cidrs

syntax: parsed = iputils.parse_cidrs(cidrs)

Gets a tabular form IPV4 network, and returns a table containg the table below address.

If invalid network table, record the error and return to other networks

ip_in_cidrs

syntax: bool, err = iputils.ip_in_cidrs(ip, cidrs)

Obtaining an IPv4 address and a character string has been parsed CIDRs table (for example. From  iputils.parse_cidrs ).

If the IP in the IP exists, a return  true or  false ; any child nodes of the specified network.

Return  nil and error messages with invalid IP's

binip_in_cidrs

syntax: bool, err = iputils.binip_in_cidrs(bin_ip, cidrs)

Get Nginx binary IPv4 address (for example.  ngx.var.binary_remote_addr ) And parsing CIDRs table (for example. From  iputils.parse_cidrs ).

If the checked IP has been expressed in binary form as available, the method here than  ip_in_cidrs() faster.

If the IP in the IP exists, a return  true or  false ; any child nodes of the specified network.

Return  nil and error messages with invalid IP's

To Do

Guess you like

Origin blog.csdn.net/ai2000ai/article/details/95306723