Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. #include <string.h>
  2.  
  3. #include <lua.h>
  4. #include <lauxlib.h>
  5. #include "luaopen.h"
  6.  
  7. static int ip_encode(lua_State *L) {
  8.   const unsigned char *s = luaL_checklstring(L, 1, NULL);
  9.   char *p, b[6];
  10.   size_t l, o = 4, n = strtol(s, &p, 10);
  11.   if (!n) return 0;
  12.   while (--o) {
  13.     if (n > 255 || *p != '.' || *(p + 1) == '.' ) return 0;
  14.     b[l++] = (char)n;
  15.     n = strtol(p + 1, &p, 10);
  16.   }
  17.   if (n > 255 || !n || *p) return 0;
  18.   b[l++] = (char)n;
  19.   if (lua_type(L, 2) != LUA_TNONE) {
  20.     n = luaL_checkinteger(L, 2);
  21.     if (n > 65536 || !n) return 0;
  22.     b[l++] = n / 256;
  23.     b[l++] = n % 256;
  24.   }
  25.   lua_pushlstring(L, b, l);
  26.   return 1;
  27. }
  28.  
  29. static int ip_decode(lua_State *L) {
  30.   size_t i, l, n;
  31.   const unsigned char *s = luaL_checklstring(L, 1, &n);
  32.   if (n != 4 && n != 6) return 0;
  33.   char b[15];
  34.   l = sprintf(b, "%d", *s);
  35.   for (i = 0; i < 3; ++i) l += sprintf(b + l, ".%d", s[i]);
  36.   lua_pushlstring(L, b, l);
  37.   if (n == 4) return 1;
  38.   lua_pushinteger(L, s[4] * 256 + s[5]);
  39.   return 2;
  40. }
  41.  
  42. static struct luaL_Reg funcs[] = {
  43.   {"encode", ip_encode},
  44.   {"decode", ip_decode},
  45.   {NULL, NULL}
  46. };
  47.  
  48. int luaopen_ipconv(lua_State *L) {
  49.     luaL_newmetatable(L, "ipconv");
  50.     luaL_newlib(L, funcs);
  51.     return 1;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement