diff --git a/tool/net/help.txt b/tool/net/help.txt index 96c699cda..06ce64f63 100644 --- a/tool/net/help.txt +++ b/tool/net/help.txt @@ -539,9 +539,10 @@ FUNCTIONS Converts UNIX timestamp to an RFC1123 string that looks like this: Mon, 29 Mar 2021 15:37:13 GMT. See formathttpdatetime.c. - FormatIp(uint32) → str - Turns integer like 0x01020304 into a string like 1.2.3.4. See also - ParseIp for the inverse operation. + FormatIp(uint32[,mask:int]) → str + Turns integer like 0x01020304 into a string like 1.2.3.4. mask is + an optional width (in bits) of the network prefix applied before + conversion. See also ParseIp for the inverse operation. GetAssetComment(path:str) → str Returns comment text associated with asset in the ZIP central diff --git a/tool/net/redbean.c b/tool/net/redbean.c index 2faab285e..f5bdd3b47 100644 --- a/tool/net/redbean.c +++ b/tool/net/redbean.c @@ -3950,10 +3950,18 @@ static int LuaGetRemoteAddr(lua_State *L) { return LuaGetAddr(L, GetRemoteAddr); } +static int MAX_CIDR = TYPE_BIT(uint32_t); static int LuaFormatIp(lua_State *L) { char b[16]; - uint32_t ip; - ip = htonl(luaL_checkinteger(L, 1)); + uint32_t ip, mask; + int cidr; + ip = luaL_checkinteger(L, 1); + cidr = luaL_optinteger(L, 2, MAX_CIDR); + if (cidr > MAX_CIDR || cidr <= 0) { + return luaL_argerror(L, 2, + gc(xasprintf("network mask not in range 1..%d", MAX_CIDR))); + } + ip = htonl(ip & (~0UL << (MAX_CIDR-cidr))); inet_ntop(AF_INET, &ip, b, sizeof(b)); lua_pushstring(L, b); return 1;