moonbridge

diff moonbridge_io.c @ 98:acaa85256c4b

Added moonbridge_io.tcpconnect(...) function
author jbe
date Wed Apr 08 04:00:41 2015 +0200 (2015-04-08)
parents 0561abcc68ee
children c9ffbdac1337
line diff
     1.1 --- a/moonbridge_io.c	Wed Apr 08 01:35:06 2015 +0200
     1.2 +++ b/moonbridge_io.c	Wed Apr 08 04:00:41 2015 +0200
     1.3 @@ -9,6 +9,8 @@
     1.4  #include <fcntl.h>
     1.5  #include <netinet/in.h>
     1.6  #include <netinet/tcp.h>
     1.7 +#include <sys/types.h>
     1.8 +#include <netdb.h>
     1.9  
    1.10  #include <lua.h>
    1.11  #include <lauxlib.h>
    1.12 @@ -482,6 +484,54 @@
    1.13    return 0;
    1.14  }
    1.15  
    1.16 +int moonbr_io_tcpconnect(lua_State *L) {
    1.17 +  const char *host, *port;
    1.18 +  struct addrinfo hints = { 0, };
    1.19 +  struct addrinfo *res, *addrinfo;
    1.20 +  int errcode;
    1.21 +  int sock;
    1.22 +  host = luaL_checkstring(L, 1);
    1.23 +  port = luaL_checkstring(L, 2);
    1.24 +  hints.ai_family = AF_UNSPEC;
    1.25 +  hints.ai_socktype = SOCK_STREAM;
    1.26 +  hints.ai_protocol = IPPROTO_TCP;
    1.27 +  hints.ai_flags = AI_ADDRCONFIG;
    1.28 +  errcode = getaddrinfo(host, port, &hints, &res);
    1.29 +  if (errcode) {
    1.30 +    if (errcode == EAI_SYSTEM) {
    1.31 +      moonbr_io_errmsg();
    1.32 +      lua_pushnil(L);
    1.33 +      lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
    1.34 +    } else {
    1.35 +      lua_pushnil(L);
    1.36 +      lua_pushstring(L, gai_strerror(errcode));
    1.37 +    }
    1.38 +    return 2;
    1.39 +  }
    1.40 +  for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
    1.41 +    if (addrinfo->ai_family == PF_INET6) goto moonbr_io_tcpconnect_found;
    1.42 +  }
    1.43 +  for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
    1.44 +    if (addrinfo->ai_family == PF_INET) goto moonbr_io_tcpconnect_found;
    1.45 +  }
    1.46 +  addrinfo = res;
    1.47 +  moonbr_io_tcpconnect_found:
    1.48 +  sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
    1.49 +  if (sock < 0) {
    1.50 +    moonbr_io_errmsg();
    1.51 +    lua_pushnil(L);
    1.52 +    lua_pushstring(L, errmsg);
    1.53 +  }
    1.54 +  if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
    1.55 +    moonbr_io_errmsg();
    1.56 +    lua_pushnil(L);
    1.57 +    lua_pushstring(L, errmsg);
    1.58 +    return 2;
    1.59 +  }
    1.60 +  moonbr_io_pushhandle(L, sock, 1);
    1.61 +  return 1;
    1.62 +}
    1.63 +
    1.64  static const struct luaL_Reg moonbr_io_handle_methods[] = {
    1.65    {"read", moonbr_io_read},
    1.66    {"read_nb", moonbr_io_read_nb},
    1.67 @@ -505,6 +555,7 @@
    1.68  };
    1.69  
    1.70  static const struct luaL_Reg moonbr_io_module_funcs[] = {
    1.71 +  {"tcpconnect", moonbr_io_tcpconnect},
    1.72    {NULL, NULL}
    1.73  };
    1.74  

Impressum / About Us