Best way to bind a socket to an IP?

What’s the best way to bind a socket to an IP (instead of a hostname)?

I got it already working by monkey patching the standard library, but maybe there is some better way!?

Example of what I try to achieve:

require "socket"

#server shall accept connections only on the machine's 127.0.0.99 interface
server = TCPServer.new("127.0.0.99", 1234)

And while I am already at it:
Is there also something built-in to start a server with some URI? Like depending of an URI, maybe tcp://127.0.0.99:1234 or unix:///foo/bar, it starts a TCPServer, UNIXServer (or UDPServer if it would have been udp://…). While not hard to implement, it is standard behaviour enough that there could be already something existing and I simply just missed it.

Wouldn’t this be Socket - Crystal 1.11.0-dev?

Not that I’m aware of?

1 Like

You are right. I didn’t check Socket itself (only the TCPServer classes and they don’t seem to provide a way for IPs).

Thanks!

This is actually implemented in HTTP::Server#bind. It could probably be extracted and generalized for Socket::Server.

3 Likes