module ActionDispatch::Http::URL

def port

req.port # => 8080
req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080'

req.port # => 80
req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com'

Returns the port number of this request as an integer.
def port
  @port ||= if raw_host_with_port =~ /:(\d+)$/
    $1.to_i
  else
    standard_port
  end
end