Mercurial > prosody-hg
comparison util-src/net.c @ 8426:8b612ec00e4a
util.net: Add bindings to inet_ntop and inet_pton
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Sun, 26 Nov 2017 02:26:13 +0100 |
| parents | 1c6a07606309 |
| children | c1d5f52274cf |
comparison
equal
deleted
inserted
replaced
| 8425:91c220f43826 | 8426:8b612ec00e4a |
|---|---|
| 123 | 123 |
| 124 #endif | 124 #endif |
| 125 return 1; | 125 return 1; |
| 126 } | 126 } |
| 127 | 127 |
| 128 static int lc_pton(lua_State *L) { | |
| 129 char buf[16]; | |
| 130 const char *ipaddr = luaL_checkstring(L, 1); | |
| 131 int errno_ = 0; | |
| 132 int family = strchr(ipaddr, ':') ? AF_INET6 : AF_INET; | |
| 133 | |
| 134 switch(inet_pton(family, ipaddr, &buf)) { | |
| 135 case 1: | |
| 136 lua_pushlstring(L, buf, family == AF_INET6 ? 16 : 4); | |
| 137 return 1; | |
| 138 | |
| 139 case -1: | |
| 140 errno_ = errno; | |
| 141 lua_pushnil(L); | |
| 142 lua_pushstring(L, strerror(errno_)); | |
| 143 lua_pushinteger(L, errno_); | |
| 144 return 3; | |
| 145 | |
| 146 default: | |
| 147 case 0: | |
| 148 lua_pushnil(L); | |
| 149 lua_pushstring(L, strerror(EINVAL)); | |
| 150 lua_pushinteger(L, EINVAL); | |
| 151 return 3; | |
| 152 } | |
| 153 | |
| 154 } | |
| 155 | |
| 156 static int lc_ntop(lua_State *L) { | |
| 157 char buf[INET6_ADDRSTRLEN]; | |
| 158 int family; | |
| 159 int errno_; | |
| 160 size_t l; | |
| 161 const char *ipaddr = luaL_checklstring(L, 1, &l); | |
| 162 | |
| 163 if(l == 16) { | |
| 164 family = AF_INET6; | |
| 165 } | |
| 166 else if(l == 4) { | |
| 167 family = AF_INET; | |
| 168 } | |
| 169 else { | |
| 170 lua_pushnil(L); | |
| 171 lua_pushstring(L, strerror(EAFNOSUPPORT)); | |
| 172 lua_pushinteger(L, EAFNOSUPPORT); | |
| 173 return 3; | |
| 174 } | |
| 175 | |
| 176 if(!inet_ntop(family, ipaddr, buf, INET6_ADDRSTRLEN)) | |
| 177 { | |
| 178 errno_ = errno; | |
| 179 lua_pushnil(L); | |
| 180 lua_pushstring(L, strerror(errno_)); | |
| 181 lua_pushinteger(L, errno_); | |
| 182 return 3; | |
| 183 } | |
| 184 | |
| 185 lua_pushstring(L, (const char *)(&buf)); | |
| 186 return 1; | |
| 187 } | |
| 188 | |
| 128 int luaopen_util_net(lua_State *L) { | 189 int luaopen_util_net(lua_State *L) { |
| 129 #if (LUA_VERSION_NUM > 501) | 190 #if (LUA_VERSION_NUM > 501) |
| 130 luaL_checkversion(L); | 191 luaL_checkversion(L); |
| 131 #endif | 192 #endif |
| 132 luaL_Reg exports[] = { | 193 luaL_Reg exports[] = { |
| 133 { "local_addresses", lc_local_addresses }, | 194 { "local_addresses", lc_local_addresses }, |
| 195 { "pton", lc_pton }, | |
| 196 { "ntop", lc_ntop }, | |
| 134 { NULL, NULL } | 197 { NULL, NULL } |
| 135 }; | 198 }; |
| 136 | 199 |
| 137 lua_createtable(L, 0, 1); | 200 lua_createtable(L, 0, 1); |
| 138 luaL_setfuncs(L, exports, 0); | 201 luaL_setfuncs(L, exports, 0); |
