1 28 package org.jruby.ext.socket; 29 30 import java.net.InetAddress ; 31 import java.net.InetSocketAddress ; 32 import java.net.UnknownHostException ; 33 34 import org.jruby.Ruby; 35 import org.jruby.RubyClass; 36 import org.jruby.exceptions.RaiseException; 37 import org.jruby.runtime.CallbackFactory; 38 import org.jruby.runtime.ObjectAllocator; 39 import org.jruby.runtime.builtin.IRubyObject; 40 41 44 public class RubyIPSocket extends RubyBasicSocket { 45 static void createIPSocket(Ruby runtime) { 46 RubyClass rb_cIPSocket = runtime.defineClass("IPSocket", runtime.getClass("BasicSocket"), IPSOCKET_ALLOCATOR); 47 CallbackFactory cfact = runtime.callbackFactory(RubyIPSocket.class); 48 49 rb_cIPSocket.defineFastMethod("addr", cfact.getFastMethod("addr")); 50 rb_cIPSocket.defineFastMethod("peeraddr", cfact.getFastMethod("peeraddr")); 51 rb_cIPSocket.getMetaClass().defineFastMethod("getaddress", cfact.getFastSingletonMethod("getaddress", IRubyObject.class)); 52 53 runtime.getObject().setConstant("IPsocket",rb_cIPSocket); 54 } 55 56 private static ObjectAllocator IPSOCKET_ALLOCATOR = new ObjectAllocator() { 57 public IRubyObject allocate(Ruby runtime, RubyClass klass) { 58 return new RubyIPSocket(runtime, klass); 59 } 60 }; 61 62 public RubyIPSocket(Ruby runtime, RubyClass type) { 63 super(runtime, type); 64 } 65 66 protected static RuntimeException sockerr(IRubyObject recv, String msg) { 67 return new RaiseException(recv.getRuntime(), recv.getRuntime().getClass("SocketError"), null, true); 68 } 69 70 private IRubyObject addrFor(InetSocketAddress addr) { 71 IRubyObject[] ret = new IRubyObject[4]; 72 Ruby r = getRuntime(); 73 ret[0] = r.newString("AF_INET"); 74 ret[1] = r.newFixnum(addr.getPort()); 75 if(r.isDoNotReverseLookupEnabled()) { 76 ret[2] = r.newString(addr.getAddress().getHostAddress()); 77 } else { 78 ret[2] = r.newString(addr.getHostName()); 79 } 80 ret[3] = r.newString(addr.getAddress().getHostAddress()); 81 return r.newArrayNoCopy(ret); 82 } 83 84 public IRubyObject addr() { 85 return addrFor(getLocalSocket()); 86 } 87 88 public IRubyObject peeraddr() { 89 return addrFor(getRemoteSocket()); 90 } 91 92 public static IRubyObject getaddress(IRubyObject recv, IRubyObject hostname) { 93 try { 94 return recv.getRuntime().newString(InetAddress.getByName(hostname.convertToString().toString()).getHostAddress()); 95 } catch(UnknownHostException e) { 96 throw sockerr(recv, "getaddress: name or service not known"); 97 } 98 } 99 } | Popular Tags |