Skip to content

BasicSocket#send sends to_s of a message that responds to to_str #10105

Open

Description

@taxor03

BasicSocket#send(mesg, flags) without a destination address converts mesg with to_str, but then writes mesg.to_s, so a message object that is not a String sends "#<Object:...>" instead of its String. With a destination address (UDP) the converted String is sent, and CRuby sends the converted String in both cases. The docs say "mesg should be a string" (BasicSocket#send), and CRuby converts it with StringValue.

require 'socket'

message = Object.new
def message.to_str = "hello"

a, b = UNIXSocket.pair
p a.send(message, 0)
p b.recv(100)

s = UDPSocket.new
s.bind("127.0.0.1", 0)
p UDPSocket.new.send(message, 0, "127.0.0.1", s.addr[1])
p s.recv(100)

CRuby 4.0.9 (ruby 4.0.9 (2026-10-23 revision 3e93b23afc) +PRISM [aarch64-linux]), and 3.4.12 and 3.3.13 print the same:

5
"hello"
5
"hello"

JRuby 10.0.8.0 (jruby 10.0.8.0 (3.4.12) 2026-11-05 ef393d4e54 OpenJDK 64-Bit Server VM 21.0.13+9-LTS on 21.0.13+9-LTS +indy +jit [aarch64-linux]):

20
"#<Object:0x6c2c1385>"
5
"hello"

JRuby 10.1.3.0 (jruby 10.1.3.0 (4.0.9) 2026-11-05 3db52d02f9 OpenJDK 64-Bit Server VM 21.0.13+9-LTS on 21.0.13+9-LTS +indy +jit [aarch64-linux]) and a build of master (54dd973) print the same.

RubyBasicSocket#doSend converts the message with _mesg.convertToString() and uses the result for a DatagramChannel with an address, but the other branch calls syswrite(context, _mesg) with the original object (RubyBasicSocket.java#L187; on master #L191), and syswrite writes its to_s. CRuby's rsock_bsock_send replaces the message with StringValue(arg.mesg) before sending (basicsocket.c#L576). Passing the converted mesg to syswrite should match CRuby.

ruby/spec's "BasicSocket#send using a disconnected socket with an object implementing #to_str returns the amount of sent bytes" (send_spec.rb#L102-L108) sends to a destination address, so it takes the branch that already uses the String.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions