Search code examples
tcplualuasocket

Communicate server port to client? (TCP)


Problem

Following LuaSocket Introduction I managed to get the server running. I also managed to connect from the client side. But to get this connection the client must know the server port number. In the example code the server port is 0, which means:

If port is 0, the system automatically chooses an ephemeral port.

I guess this approach has it's advantages, but how does the poor client is supposed to know which port to connect to?

Question

How to communicate an ephemeral port number from server to client? I assume there should be no human action in the process.

Code

server (from LuaSocket Introduction)

-- load namespace
local socket = require("socket")
-- create a TCP socket and bind it to the local host, at any port
local server = assert(socket.bind("*", 0))
-- find out which port the OS chose for us
local ip, port = server:getsockname()
-- print a message informing what's up
print("Please telnet to localhost on port " .. port)
print("After connecting, you have 10s to enter a line to be echoed")
-- loop forever waiting for clients
while 1 do
  -- wait for a connection from any client
  local client = server:accept()
  -- make sure we don't block waiting for this client's line
  client:settimeout(10)
  -- receive the line
  local line, err = client:receive()
  -- if there was no error, send it back to the client
  if not err then client:send(line .. "\n") end
  -- done with client, close the object
  client:close()
end

client (follows this answer)

local host, port = "127.0.0.1", 100
local socket = require("socket")
local tcp = assert(socket.tcp())

tcp:connect(host, port);
--note the newline below
tcp:send("hello world\n");

while true do
    local s, status, partial = tcp:receive()
    print(s or partial)
    if status == "closed" then break end
end
tcp:close()

Solution

  • How to communicate an ephemeral port number from server to client? I assume there should be no human action in the process.I assume there should be no human action in the process.

    You are right. The server example is quite odd. The servers generally should bind to specific port. It shouldn't be ephemeral. So that when the server restarts the client connects to the same port as earlier. Otherwise, the clients would be at loss if server ports keeps changing.

    Clients, can indeed bind to ephemeral ports ( they generally do ). Servers should be bound to specific ones.