Skip to content
This repository
Browse code

JRUBY-4868: Socket.getservbyname doesn't accept string port argument

Regression test added as well.
  • Loading branch information...
commit 7ceaee3430b9642c20d0b846b983f3e6357e8893 1 parent 8186bc4
Vladimir Sizikov vvs authored
20 src/org/jruby/ext/socket/RubySocket.java
@@ -316,22 +316,34 @@ public static IRubyObject gethostbyaddr(ThreadContext context, IRubyObject recv,
316 316 ret[3] = args[0];
317 317 return runtime.newArrayNoCopy(ret);
318 318 }
  319 +
319 320 @Deprecated
320 321 public static IRubyObject getservbyname(IRubyObject recv, IRubyObject[] args) {
321 322 return getservbyname(recv.getRuntime().getCurrentContext(), recv, args);
322 323 }
  324 +
323 325 @JRubyMethod(required = 1, optional = 1, meta = true)
324 326 public static IRubyObject getservbyname(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
325 327 Ruby runtime = context.getRuntime();
326 328 int argc = Arity.checkArgumentCount(runtime, args, 1, 2);
327 329 String name = args[0].convertToString().toString();
328 330 String proto = argc == 1 ? "tcp" : args[1].convertToString().toString();
329   -
  331 +
330 332 jnr.netdb.Service service = jnr.netdb.Service.getServiceByName(name, proto);
331   - if(service == null) {
332   - throw sockerr(runtime, "no such service " + name + "/" + proto);
  333 +
  334 + int port;
  335 + if (service != null) {
  336 + port = service.getPort();
  337 + } else {
  338 + // MRI behavior: try to convert the name string to port directly
  339 + try {
  340 + port = Integer.parseInt(name.trim());
  341 + } catch (NumberFormatException nfe) {
  342 + throw sockerr(runtime, "no such service " + name + "/" + proto);
  343 + }
333 344 }
334   - return runtime.newFixnum(service.getPort());
  345 +
  346 + return runtime.newFixnum(port);
335 347 }
336 348
337 349 @Deprecated
8 test/test_socket.rb
@@ -105,6 +105,13 @@ def test_udp_socket_reuse_addr
105 105 ensure
106 106 socket.close
107 107 end
  108 +
  109 + # JRUBY-4868
  110 + def test_getservbyname
  111 + assert_equal(21, Socket.getservbyname('ftp'))
  112 + assert_equal(21, Socket.getservbyname('21'))
  113 + assert_equal(21, Socket.getservbyname(' 21'))
  114 + end
108 115 end
109 116
110 117 class UNIXSocketTests < Test::Unit::TestCase
@@ -370,7 +377,6 @@ def test_can_read_and_get_minus_one
370 377 sock1.recv(1)
371 378 end
372 379 end
373   -
374 380 end
375 381 end
376 382

0 comments on commit 7ceaee3

Please sign in to comment.
Something went wrong with that request. Please try again.