Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string.h>
- #include <lua.h>
- #include <lauxlib.h>
- #include "luaopen.h"
- static int ip_encode(lua_State *L) {
- const unsigned char *s = luaL_checklstring(L, 1, NULL);
- char *p, b[6];
- size_t l, o = 4, n = strtol(s, &p, 10);
- if (!n) return 0;
- while (--o) {
- if (n > 255 || *p != '.' || *(p + 1) == '.' ) return 0;
- b[l++] = (char)n;
- n = strtol(p + 1, &p, 10);
- }
- if (n > 255 || !n || *p) return 0;
- b[l++] = (char)n;
- if (lua_type(L, 2) != LUA_TNONE) {
- n = luaL_checkinteger(L, 2);
- if (n > 65536 || !n) return 0;
- b[l++] = n / 256;
- b[l++] = n % 256;
- }
- lua_pushlstring(L, b, l);
- return 1;
- }
- static int ip_decode(lua_State *L) {
- size_t i, l, n;
- const unsigned char *s = luaL_checklstring(L, 1, &n);
- if (n != 4 && n != 6) return 0;
- char b[15];
- l = sprintf(b, "%d", *s);
- for (i = 0; i < 3; ++i) l += sprintf(b + l, ".%d", s[i]);
- lua_pushlstring(L, b, l);
- if (n == 4) return 1;
- lua_pushinteger(L, s[4] * 256 + s[5]);
- return 2;
- }
- static struct luaL_Reg funcs[] = {
- {"encode", ip_encode},
- {"decode", ip_decode},
- {NULL, NULL}
- };
- int luaopen_ipconv(lua_State *L) {
- luaL_newmetatable(L, "ipconv");
- luaL_newlib(L, funcs);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement