Robert Klemme
12/3/2006 1:30:00 PM
Arie Hofland wrote:
> First off - i'm a n00b at ruby. This doesn't mean i'm a noob at
> programming, but in case i'm about to ask a really stupid question,
> sorry in advance :P
>
> With that out of the way, i'm trying to connect to an IP-address
> (Specifically an ED2K server) and get information out of it. At first,
> simply nothing happened. When i tried to build in a control mechanism,
> something weird happened: It told me i was trying to connect to myself!
>
> ----
> Code:
>
> require 'socket'
> t = TCPSocket.new('62.241.53.16', '4242')
> print "Connecting to " + t.addr[3].to_s + ":" + t.addr[1].to_s
> t.recv(100)
> print "Closing Connection"
> t.close
>
> Result:
>
> Connecting to 192.168.2.6:4182
> ----
>
> So am i misinterpreting the addr value, or is my program (or possibly
> the server i'm trying to connect to) doing some weird things?
You are misinterpreting: addr is your own address. After all you *know*
the other address already - otherwise you would not have been able to
connect.
Another small hint: preferably use the block form whenever possible:
require 'socket'
TCPSocket.open('62.241.53.16', 4242) do |t|
p t.addr
p t.recv(100)
puts "Closing Connection"
end
You can use t.getpeername to obtain a struct sockaddr which you need to
unpack to get at the family, address and port of the remote machine:
irb(main):045:0> t=TCPSocket.open('62.241.53.16', 4242)
=> #<TCPSocket:0x3883a8>
irb(main):046:0> t.getpeername
=> "\002\000\020\222>\3615\020\000\000\000\000\000\000\000\000"
irb(main):047:0> t.getpeername.unpack "S"
=> [2]
irb(main):048:0> t.getpeername.unpack "nnC4"
=> [512, 4242, 62, 241, 53, 16]
irb(main):064:0> fam, port, *addr = t.getpeername.unpack "nnC4"
=> [512, 4242, 62, 241, 53, 16]
irb(main):065:0> fam
=> 512
irb(main):066:0> port
=> 4242
irb(main):067:0> addr
=> [62, 241, 53, 16]
irb(main):070:0> addr.join '.'
=> "62.241.53.16"
HTH
Kind regards
robert