diff options
| author | ruki <[email protected]> | 2019-10-13 00:03:03 +0800 |
|---|---|---|
| committer | ruki <[email protected]> | 2019-10-13 00:03:03 +0800 |
| commit | 9d3eab796916f907a5fc95b4333791ee2ac6df49 (patch) | |
| tree | 7e8ff814b05139c11ef3cf3276f0b0f43fbd4f66 | |
| parent | 18468a7582fa6b277380a752ff3b7a2a37bc77bd (diff) | |
implement to open socket
| -rw-r--r-- | core/src/xmake/io/socket_open.c | 40 | ||||
| -rw-r--r-- | xmake/core/base/io/socket.lua | 10 |
2 files changed, 46 insertions, 4 deletions
diff --git a/core/src/xmake/io/socket_open.c b/core/src/xmake/io/socket_open.c index 1c50c9d37..647cd247e 100644 --- a/core/src/xmake/io/socket_open.c +++ b/core/src/xmake/io/socket_open.c @@ -35,15 +35,51 @@ */ /* - * io.socket_open() + * io.socket_open(socktype, family) */ tb_int_t xm_io_socket_open(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); + // get socket type + tb_char_t const* socktype = luaL_checkstring(lua, 1); + tb_assert_and_check_return_val(socktype, 0); + + // get address family + tb_char_t const* family = luaL_checkstring(lua, 2); + tb_assert_and_check_return_val(family, 0); + + // map socket type + tb_size_t t = TB_SOCKET_TYPE_NONE; + if (!tb_strcmp(socktype, "tcp")) + t = TB_SOCKET_TYPE_TCP; + else if (!tb_strcmp(socktype, "udp")) + t = TB_SOCKET_TYPE_UDP; + else if (!tb_strcmp(socktype, "icmp")) + t = TB_SOCKET_TYPE_ICMP; + else + { + lua_pushnil(lua); + lua_pushliteral(lua, "invalid socket type!"); + return 2; + } + + // map address family + tb_size_t f = TB_IPADDR_FAMILY_NONE; + if (!tb_strcmp(family, "ipv4")) + f = TB_IPADDR_FAMILY_IPV4; + else if (!tb_strcmp(family, "ipv6")) + f = TB_IPADDR_FAMILY_IPV6; + else + { + lua_pushnil(lua); + lua_pushliteral(lua, "invalid address family!"); + return 2; + } + // init socket - tb_socket_ref_t sock = tb_socket_init(TB_SOCKET_TYPE_TCP, TB_IPADDR_FAMILY_IPV4); + tb_socket_ref_t sock = tb_socket_init(t, f); if (sock) lua_pushlightuserdata(lua, (tb_pointer_t)sock); else lua_pushnil(lua); return 1; diff --git a/xmake/core/base/io/socket.lua b/xmake/core/base/io/socket.lua index 9f26d82ed..53eb934bd 100644 --- a/xmake/core/base/io/socket.lua +++ b/xmake/core/base/io/socket.lua @@ -84,11 +84,17 @@ function _socket:__gc() end -- open a socket +-- +-- @param socktype the socket type, e.g. tcp, udp, icmp +-- @param family the address family, e.g. ipv4, ipv6 +-- +-- @return the socket instance +-- function io.opensock(socktype, family) - local sock = io.socket_open(socktype, family) + local sock, errors = io.socket_open(socktype, family) if sock then return _socket.new(socktype, family, sock) else - return nil, string.format("failed to open socket!") + return nil, errors or string.format("failed to open socket(%s/%s)!", socktype, family) end end |
