Skip to content

Commit

Permalink
Allow creating sockets from raw file descriptors
Browse files Browse the repository at this point in the history
This is useful for socket activation, sandboxes, etc.
  • Loading branch information
valpackett committed Sep 30, 2018
1 parent 07f91d7 commit 430e760
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/socket.cr
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class Socket < IO
end
end

protected def initialize(@fd : Int32, @family, @type, @protocol = Protocol::IP, blocking = false)
def initialize(@fd : Int32, @family, @type, @protocol = Protocol::IP, blocking = false)
@closed = false
init_close_on_exec(@fd)

Expand Down
5 changes: 5 additions & 0 deletions src/socket/tcp_server.cr
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ class TCPServer < TCPSocket
end
end

# Creates a TCPServer from an already configured raw file descriptor
def initialize(fd : Int32, family : Family = Family::INET)
super(fd, family)
end

# Creates a new TCP server, listening on all local interfaces (`::`).
def self.new(port : Int, backlog = SOMAXCONN, reuse_port = false)
new("::", port, backlog, reuse_port: reuse_port)
Expand Down
5 changes: 5 additions & 0 deletions src/socket/tcp_socket.cr
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ class TCPSocket < IPSocket
super fd, family, type, protocol
end

# Creates a TCPSocket from an already configured raw file descriptor
def initialize(fd : Int32, family : Family = Family::INET)
super fd, family, Type::STREAM, Protocol::TCP
end

# Opens a TCP socket to a remote TCP server, yields it to the block, then
# eventually closes the socket when the block returns.
#
Expand Down
5 changes: 5 additions & 0 deletions src/socket/unix_server.cr
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ class UNIXServer < UNIXSocket
end
end

# Creates a UNIXServer from an already configured raw file descriptor
def initialize(fd : Int32, type : Type = Type::STREAM, @path : String? = nil)
super(fd, type, path)
end

# Creates a new UNIX server and yields it to the block. Eventually closes the
# server socket when the block returns.
#
Expand Down
3 changes: 2 additions & 1 deletion src/socket/unix_socket.cr
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ class UNIXSocket < Socket
super family, type, Protocol::IP
end

protected def initialize(fd : Int32, type : Type, @path : String? = nil)
# Creates a UNIXSocket from an already configured raw file descriptor
def initialize(fd : Int32, type : Type = Type::STREAM, @path : String? = nil)
super fd, Family::UNIX, type, Protocol::IP
end

Expand Down

0 comments on commit 430e760

Please sign in to comment.