1# simple webpage fetcher
2
3# The code demonstrates how a multi-protocol client should be written.
4# TCPSocket is using getaddrinfo() internally, so there should be no problem.
5
6require "socket"
7
8if ARGV.size != 1
9  STDERR.print "requires URL\n"
10  exit
11end
12
13url = ARGV[0]
14if url !~ /^http:\/\/([^\/]+)(\/.*)$/
15  STDERR.print "only http with full hostname is supported\n"
16  exit
17end
18
19# split URL into host, port and path
20hostport = $1
21path = $2
22if (hostport =~ /^(.*):([0-9]+)$/)
23  host = $1
24  port = $2
25else
26  host = hostport
27  port = 80
28end
29if host =~ /^\[(.*)\]$/
30  host = $1
31end
32
33#STDERR.print "url=<#{ARGV[0]}>\n"
34#STDERR.print "host=<#{host}>\n"
35#STDERR.print "port=<#{port}>\n"
36#STDERR.print "path=<#{path}>\n"
37
38STDERR.print "conntecting to #{host} port #{port}\n"
39c = TCPSocket.new(host, port)
40dest = Socket.getnameinfo(c.getpeername,
41		Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV)
42STDERR.print "conntected to #{dest[0]} port #{dest[1]}\n"
43c.print "GET #{path} HTTP/1.0\n"
44c.print "Host: #{host}\n"
45c.print "\n"
46while c.gets
47  print
48end
49