Skip to content

Add net/socket for unbound socket creation for #1622#1623

Merged
bakpakin merged 1 commit intojanet-lang:masterfrom
tttuuu888:work-issue-1622
Aug 16, 2025
Merged

Add net/socket for unbound socket creation for #1622#1623
bakpakin merged 1 commit intojanet-lang:masterfrom
tttuuu888:work-issue-1622

Conversation

@tttuuu888
Copy link
Contributor

This PR add a new core function, net/socket, to create an unbound network socket.
I believe this is useful for handling flexible port assignments, as seen in protocols like TFTP.

And the following are Janet server/client codes that implement the server/client examples attached to issue #1622, using the net/socket API added in this PR.

Server:

# 1. Create and bind a socket
(def listen-sock (net/listen "127.0.0.1" 8080 :datagram))
(print "Server listening on 127.0.0.1:8080")

# 2. Receive the client's message
(def buff (buffer/new 1024))
(def recv-info (net/recv-from listen-sock 1024 buff))
(print "Server received: " buff " from port " ((net/address-unpack recv-info) 1))

# 3. Send "world" message from a new socket
(def world-msg "world")
(def new-sock (net/socket :datagram))
(net/send-to new-sock recv-info world-msg)
(print "Server sent: " world-msg)

(net/close listen-sock)
(net/close new-sock)

Client:

# 1. Create a socket (without binding)
(def client-sock (net/socket :datagram))
(def server-addr (net/address "127.0.0.1" 8080))
(print "Client socket created for server at 127.0.0.1:8080")

# 2. Send "hello" message to the server
(def hello-msg "hello")
(net/send-to client-sock server-addr hello-msg)
(print "Client sent: " hello-msg)

# 3. Receive the server's response
(def buff (buffer/new 1024))
(def recv-info (net/recv-from client-sock 1024 buff))
(print "Client received: " hello-msg " from port " ((net/address-unpack recv-info) 1))
(net/close client-sock)

I have confirmed that the C server - Janet client and Janet server - C client combinations also work correctly.

Thank you in advance for the review.
If net/socket is unnecessary and there's another way to implement the behavior described in issue #1622, I'd appreciate it if you could share that with me.

Thank you.

@bakpakin
Copy link
Member

The code looks good and the justification reasonable - thanks again, @tttuuu888 .

It does seem to me that we will probably want a "bind" function for these new unbound sockets, although I'm not sure of the exact use case and that would be a separate issue.

@bakpakin bakpakin merged commit bf34340 into janet-lang:master Aug 16, 2025
13 checks passed
@tttuuu888 tttuuu888 deleted the work-issue-1622 branch August 16, 2025 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants