### Successful parse example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Successful parse example for RemoteIp.Block.parse/1. ```elixir {:ok, block} = RemoteIp.Block.parse("10.0.0.0/8") ``` -------------------------------- ### Basic plug setup with RemoteIp Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Shows a minimal Plug.Router that plugs RemoteIp with the x-forwarded-for header and responds with the remote IP. ```elixir defmodule MyApp do use Plug.Router plug RemoteIp, headers: ~w[x-forwarded-for] plug :match plug :dispatch get "/" do send_resp(conn, 200, "remote ip: #{:inet.ntoa(conn.remote_ip)}") end end ``` -------------------------------- ### parse!/1 CIDR example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of parsing a CIDR block. ```elixir RemoteIp.Block.parse!("1.2.3.0/24") # => %RemoteIp.Block{proto: :v4, net: 16909056, mask: 4294967040} ``` -------------------------------- ### Example: to_string(RemoteIp.Block.parse!("1.2.0.0/16")) Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of converting a parsed block to a CIDR string. The output is the same as the input string. ```elixir to_string(RemoteIp.Block.parse!("1.2.0.0/16")) # => "1.2.0.0/16" ``` -------------------------------- ### contains?/2 membership example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of membership check: true for IP inside the block, false for outside. ```elixir block = RemoteIp.Block.parse!("192.168.0.0/24") RemoteIp.Block.contains?(block, RemoteIp.Block.encode({192, 168, 0, 42})) # => true RemoteIp.Block.contains?(block, RemoteIp.Block.encode({8, 8, 8, 8})) # => false ``` -------------------------------- ### Error handling examples Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parsers_forwarded.md Shows that invalid input returns an empty list, and that 'unknown' and obfuscated identifiers are ignored. ```elixir RemoteIp.Parsers.Forwarded.parse("invalid") # => [] ``` ```elixir RemoteIp.Parsers.Forwarded.parse("for=unknown, for=_obfuscated") # => [] ``` -------------------------------- ### Basic for= pair example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parsers_forwarded.md Parses a simple header with a single 'for=' pair and returns the IP tuple. ```elixir RemoteIp.Parsers.Forwarded.parse("for=1.2.3.4;by=2.3.4.5") # => [{1, 2, 3, 4}] ``` -------------------------------- ### encode/1 IPv4 example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of encoding an IPv4 tuple. ```elixir RemoteIp.Block.encode({192, 168, 0, 1}) # => {:v4, 3232235521} ``` -------------------------------- ### take/2 duplicate headers example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/headers.md Demonstrates that take/2 preserves duplicate headers with the same name, returning all matching pairs in the original order. ```elixir headers = [{"x-dup", "foo"}, {"x-dup", "bar"}, {"x-dup", "baz"}] RemoteIp.Headers.take(headers, ["x-dup"]) # => [{"x-dup", "foo"}, {"x-dup", "bar"}, {"x-dup", "baz"}] ``` -------------------------------- ### encode/1 IPv6 example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of encoding an IPv6 tuple. ```elixir RemoteIp.Block.encode({0, 0, 0, 0, 0, 0, 0, 1}) # => {:v6, 1} ``` -------------------------------- ### parse/2 mixed header example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/headers.md Shows parse/2 with comma-separated values and RFC 7239 Forwarded headers. The first example parses two headers with comma-separated IPs, returning a flat list. The second mixes a Forwarded header and an X-Forwarded-For header, demonstrating the default parser behavior. ```elixir RemoteIp.Headers.parse([{"x-one", "1.2.3.4, 2.3.4.5"}, {"x-two", "3.4.5.6, 4.5.6.7"}]) # => [{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}] RemoteIp.Headers.parse([{"forwarded", "for=1.2.3.4"}, {"x-forwarded-for", "2.3.4.5"}]) # => [{1, 2, 3, 4}, {2, 3, 4, 5}] ``` -------------------------------- ### Example headers with spoofed Forwarded header Source: https://github.com/ajvondrak/remote_ip/blob/main/extras/algorithm.md Shows the list of headers when a client sends a spoofed Forwarded header. The headers are parsed into a list of IP tuples, demonstrating the order of IPs from the chain. ```elixir [{"forwarded", "for=6.7.8.9"}, {"x-forwarded-for", "1.2.3.4, 1.1.1.1"}, {"forwarded", "for=2.2.2.2"}] ``` ```elixir [{6, 7, 8, 9}, {1, 2, 3, 4}, {1, 1, 1, 1}, {2, 2, 2, 2}] ``` -------------------------------- ### Concatenated IP list from all parsers Source: https://github.com/ajvondrak/remote_ip/blob/main/extras/algorithm.md Shows the resulting IP list after concatenating the parsed IPs from all configured headers, as in the running example. ```elixir [{1, 2, 3, 4}, {1, 1, 1, 1}, {2, 2, 2, 2}] ``` -------------------------------- ### parse!/1 error handling example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of error handling: invalid input raises ArgumentError with the message "Invalid address ... in CIDR ...". ```elixir try do RemoteIp.Block.parse!("not_an_ip") rescue e in ArgumentError -> IO.puts("bad CIDR: " <> e.message) end # => "bad CIDR: Invalid address \"not_an_ip\" in CIDR \"not_an_ip\"" ``` -------------------------------- ### Desired header list for X-Forwarded-For and Forwarded Source: https://github.com/ajvondrak/remote_ip/blob/main/extras/algorithm.md Shows the desired order of headers when both X-Forwarded-For and Forwarded are present, as in the running example. The order matters because it reflects the proxy chain. ```elixir # This is what we want [{"x-forwarded-for", "1.2.3.4, 1.1.1.1"}, {"forwarded", "for=2.2.2.2"}] ``` -------------------------------- ### Example custom parser: SpecialParser Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parser.md Implements a custom parser that strips an 'ip=' prefix and parses the remaining string as an IP address. Returns an empty list on invalid input. ```elixir defmodule SpecialParser do @behaviour RemoteIp.Parser @impl RemoteIp.Parser def parse(header) do ip = String.replace_prefix(header, "ip=", "") case :inet.parse_strict_address(ip |> to_charlist()) do {:ok, parsed} -> [parsed] _ -> [] end end end ``` -------------------------------- ### take/2 basic filtering example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/headers.md Shows basic filtering with take/2: only headers whose names are in the provided list are returned, in the same order as the input. Headers not in the list (like "x-bar") are omitted. ```elixir headers = [{"x-foo", "foo"}, {"x-bar", "bar"}, {"x-baz", "baz"}] RemoteIp.Headers.take(headers, ["x-foo", "x-baz", "x-qux"]) # => [{"x-foo", "foo"}, {"x-baz", "baz"}] ``` -------------------------------- ### contains?/2 family mismatch example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Example of family mismatch: returns false when IP family differs from block. ```elixir v4_block = RemoteIp.Block.parse!("10.0.0.0/8") RemoteIp.Block.contains?(v4_block, RemoteIp.Block.encode({0, 0, 0, 0, 0, 0, 0, 1})) # => false ``` -------------------------------- ### Using RemoteIp.from/2 in a Phoenix Socket Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Example of using RemoteIp.from/2 within a Phoenix Socket's connect/3 callback, passing options for headers, proxies, and clients. Returns nil when no client is found in the headers. ```elixir defmodule MyApp.MySocket do use Phoenix.Socket @options [ headers: ~w[x-real-ip], proxies: ~w[1.2.0.0/16], clients: ~w[1.2.3.4] ] def connect(params, socket, connect_info) do ip = RemoteIp.from(connect_info[:x_headers], @options) # returns nil when no client is found in the headers case ip do nil -> {:error, :no_ip} ip -> {:ok, socket} end end end ``` -------------------------------- ### Example error-safe parser: LenientParser Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parser.md Implements a parser that splits a comma-separated header value, trims each part, and parses each as an IP address, ignoring invalid entries. ```elixir defmodule LenientParser do @behaviour RemoteIp.Parser @impl RemoteIp.Parser def parse(value) do value |> String.split(",") |> Enum.map(&String.trim/1) |> Enum.flat_map(fn string -> case :inet.parse_strict_address(string |> to_charlist()) do {:ok, ip} -> [ip] {:error, _} -> [] end end) end end ``` -------------------------------- ### parse/2 custom parsers example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/headers.md Demonstrates that unknown headers fall back to RemoteIp.Parsers.Generic, ignoring non-IP values. Also shows passing a custom parser map to replace the default Forwarded parser for a header that does not use RFC 7239 syntax. ```elixir headers = [{"accept", "*/*"}, {"user-agent", "ua"}, {"x-real-ip", "1.2.3.4"}] RemoteIp.Headers.parse(headers) # => [{1, 2, 3, 4}] # With a custom parser map: RemoteIp.Headers.parse( [{"forwarded", "1.2.3.4"}], # not RFC 7239 syntax %{"forwarded" => MyCustomParser} # replaces the default Forwarded parser ) ``` -------------------------------- ### Handling error tuple example Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Handles the error tuple returned by RemoteIp.Block.parse/1. The output shows the error message for an invalid prefix. ```elixir case RemoteIp.Block.parse("1.2.3.4/99") do {:ok, block} -> block {:error, message} -> IO.puts("Could not parse: " <> message) end # => "Could not parse: Invalid prefix 99 in CIDR \"1.2.3.4/99\"" ``` -------------------------------- ### Extract remote IP with RemoteIp.from/2 Source: https://github.com/ajvondrak/remote_ip/blob/main/README.md Uses RemoteIp.from/2 outside a plug pipeline to extract the remote IP from a list of headers. The example passes a list with an x-forwarded-for header. ```elixir x_headers = [{"x-forwarded-for", "1.2.3.4"}] RemoteIp.from(x_headers) ``` -------------------------------- ### Add :remote_ip dependency in mix.exs Source: https://github.com/ajvondrak/remote_ip/blob/main/README.md Adds the :remote_ip package to the project's dependencies in mix.exs. Use this to install the plug. ```elixir def deps do [{:remote_ip, "~> 1.2"}] end ``` -------------------------------- ### init/1 callback implementation Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Implements the Plug.init/1 callback, packing options via RemoteIp.Options.pack/1. Non-MFA :proxies/:clients values are evaluated eagerly, so invalid CIDR strings raise ArgumentError at init time. ```elixir @impl Plug def init(opts) do RemoteIp.Options.pack(opts) end ``` -------------------------------- ### Configure RemoteIp plug with all options Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/configuration.md Shows all four constructor options passed to the RemoteIp plug in a Plug.Router module. The :headers option is set to a singleton list to avoid ambiguity and spoofing, and :parsers maps a header to a custom parser module. :proxies and :clients accept IP/CIDR strings; invalid CIDR strings raise ArgumentError. ```elixir defmodule MyApp do use Plug.Router plug RemoteIp, headers: ~w[x-real-ip], parsers: %{"x-real-ip" => MyApp.RealIpParser}, proxies: ~w[1.2.0.0/16], clients: ~w[1.2.3.4] plug :match plug :dispatch end ``` -------------------------------- ### init/1 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Initializes the RemoteIp plug with the given options. This is the `c:Plug.init/1` callback, typically called at compile time when the plug is used in a pipeline. ```APIDOC ## init/1 ### Description Initializes the RemoteIp plug with the given options. This is the `c:Plug.init/1` callback, typically called at compile time when the plug is used in a pipeline. ### Method init ### Endpoint RemoteIp.init/1 ### Parameters - **opts** (keyword()) - Required - The keyword options documented in `RemoteIp.Options` (`:headers`, `:parsers`, `:proxies`, `:clients`). Any option may be a literal value or an MFA tuple `{module, function, arguments}`. ### Return Value A `keyword()` — the packed options produced by `RemoteIp.Options.pack/1`. Runtime options (MFAs) are not evaluated here; they are deferred until `call/2`. ### Example ```elixir defmodule MyApp do use Plug.Router plug RemoteIp, headers: ~w[x-forwarded-for] plug :match plug :dispatch get "/" do send_resp(conn, 200, "remote ip: #{:inet.ntoa(conn.remote_ip)}") end end ``` ``` -------------------------------- ### Unpack MFA with application env Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Demonstrates unpacking an MFA that fetches a proxy list from the application environment. The MFA is applied during unpack, and the resulting CIDR string is parsed into a RemoteIp.Block struct. ```elixir opts = RemoteIp.Options.pack(proxies: {Application, :get_env, [:my_app, :proxies]}) Application.put_env(:my_app, :proxies, ["10.0.0.0/8"]) RemoteIp.Options.unpack(opts) # => [..., proxies: [%RemoteIp.Block{proto: :v4, net: 167772160, mask: 4278190080}], ...] ``` -------------------------------- ### Run IP checking benchmark with mix run check.exs Source: https://github.com/ajvondrak/remote_ip/blob/main/bench/README.md Run the IP checking benchmark with `mix run check.exs`. The benchmark parses CIDRs and encodes IPs as integers ahead of time to avoid conflating performance; the output shows the benchee configuration and comparison table. ```console $ mix run check.exs Randomizing with seed 570890 Operating System: macOS CPU Information: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz Number of Available Cores: 8 Available memory: 16 GB Elixir 1.11.4 Erlang 23.2.7 Benchmark suite executing with the following configuration: warmup: 2 s time: 5 s memory time: 0 ns parallel: 1 inputs: none specified Estimated total run time: 28 s Benchmarking cider... Benchmarking cidr... Benchmarking inet_cidr... Benchmarking remote_ip... Generated tmp/check.html Generated tmp/check_cider.html Generated tmp/check_cidr.html Generated tmp/check_comparison.html Generated tmp/check_inet_cidr.html Generated tmp/check_remote_ip.html Name ips average deviation median 99th % remote_ip 14.60 68.50 ms ±1.43% 68.65 ms 70.67 ms cider 10.68 93.66 ms ±2.41% 93.86 ms 97.84 ms inet_cidr 6.37 156.88 ms ±2.89% 157.15 ms 165.46 ms cidr 1.53 652.73 ms ±0.91% 652.71 ms 661.14 ms Comparison: remote_ip 14.60 cider 10.68 - 1.37x slower +25.16 ms inet_cidr 6.37 - 2.29x slower +88.38 ms cidr 1.53 - 9.53x slower +584.23 ms ``` -------------------------------- ### Calling callbacks manually Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Shows how to invoke RemoteIp.init/1 and RemoteIp.call/2 directly, equivalent to plug dispatch, and the resulting remote_ip value. ```elixir opts = RemoteIp.init(headers: ~w[x-forwarded-for]) conn = %Plug.Conn{remote_ip: {86, 75, 30, 9}, req_headers: [{"x-forwarded-for", "1.2.3.4"}]} new_conn = RemoteIp.call(conn, opts) new_conn.remote_ip # => {1, 2, 3, 4} ``` -------------------------------- ### Run CIDR parsing benchmark with mix run parse.exs Source: https://github.com/ajvondrak/remote_ip/blob/main/bench/README.md Run the CIDR parsing benchmark with `mix run parse.exs`. The output shows the benchee configuration, generated HTML reports, and a comparison table where higher iterations per second (ips) are better. ```console $ mix run parse.exs Randomizing with seed 294598 Operating System: macOS CPU Information: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz Number of Available Cores: 8 Available memory: 16 GB Elixir 1.11.4 Erlang 23.2.7 Benchmark suite executing with the following configuration: warmup: 2 s time: 5 s memory time: 0 ns parallel: 1 inputs: none specified Estimated total run time: 28 s Benchmarking cider... Benchmarking cidr... Benchmarking inet_cidr... Benchmarking remote_ip... Generated tmp/parse.html Generated tmp/parse_cider.html Generated tmp/parse_cidr.html Generated tmp/parse_comparison.html Generated tmp/parse_inet_cidr.html Generated tmp/parse_remote_ip.html Name ips average deviation median 99th % cider 269.94 3.70 ms ±7.72% 3.61 ms 4.74 ms remote_ip 264.49 3.78 ms ±9.78% 3.70 ms 5.22 ms inet_cidr 243.27 4.11 ms ±9.25% 4.08 ms 5.51 ms cidr 169.52 5.90 ms ±11.24% 5.77 ms 7.79 ms Comparison: cider 269.94 remote_ip 264.49 - 1.02x slower +0.0763 ms inet_cidr 243.27 - 1.11x slower +0.41 ms cidr 169.52 - 1.59x slower +2.19 ms ``` -------------------------------- ### Use MFA tuple for runtime :proxies option Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/configuration.md Demonstrates passing an MFA tuple {module, function, arguments} as the :proxies option. The function is applied at runtime on each call to RemoteIp.call/2 or RemoteIp.from/2 and must return a list of IP/CIDR strings. MFAs are re-evaluated per request, so expensive work should be cached. ```elixir defmodule RuntimeApp do use Plug.Router plug RemoteIp, proxies: {__MODULE__, :proxies, []} plug :match plug :dispatch def proxies do System.get_env("PROXIES") |> String.split(",", trim: true) end end ``` -------------------------------- ### Runtime MFA options resolved at call time Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Shows how to use an MFA tuple for :proxies so the environment is read on every request, not at compile time. ```elixir defmodule MyApp do use Plug.Router plug RemoteIp, proxies: {__MODULE__, :proxies, []} plug :match plug :dispatch def proxies do System.get_env("PROXIES") |> String.split(",", trim: true) end end # The environment is read on every request, not at compile time. ``` -------------------------------- ### Basic usage of RemoteIp.from/2 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Shows a basic call to RemoteIp.from/2 with a single x-forwarded-for header, returning the IP tuple {1, 2, 3, 4}. ```elixir x_headers = [{"x-forwarded-for", "1.2.3.4"}] RemoteIp.from(x_headers) # => {1, 2, 3, 4} ``` -------------------------------- ### Pack options into canonical list Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Packs raw user options into a keyword list with the four canonical keys. Missing keys are filled with default values, and MFA tuples are preserved for later evaluation by unpack/1. ```elixir def pack(options) do [ headers: pack(options, :headers), parsers: pack(options, :parsers), proxies: pack(options, :proxies), clients: pack(options, :clients) ] end ``` -------------------------------- ### Catch FunctionClauseError from RemoteIp.Block.encode/1 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/errors.md Shows how to catch a FunctionClauseError raised by RemoteIp.Block.encode/1 when called with a tuple of wrong arity (e.g., {1, 2, 3}). The example uses a case expression with a rescue clause to handle the error and print a message. ```elixir case RemoteIp.Block.encode({1, 2, 3}) do # wrong arity _ -> :ok else error in FunctionClauseError -> IO.puts("Unexpected IP shape: #{Exception.message(error)}") end ``` -------------------------------- ### Wiring custom parsers via :parsers option Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parser.md Shows how to configure RemoteIp with a custom parser for the 'x-special' header using the :parsers option. ```elixir plug RemoteIp, headers: ~w[x-special], parsers: %{"x-special" => SpecialParser} ``` -------------------------------- ### pack/1 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Processes keyword options, delaying the evaluation of MFA tuples until unpack/1. Fills missing keys with defaults and preserves MFA tuples verbatim. ```APIDOC ## `pack/1` ### Description Processes keyword options, delaying the evaluation of MFA tuples until `unpack/1`. Missing keys are filled with `default/1` values. MFA tuples are preserved verbatim (not yet applied). ### Method `pack/1` ### Parameters - `options` (keyword()) - Required - Raw user options. ### Return Value A `keyword()` with the four canonical keys `:headers`, `:parsers`, `:proxies`, `:clients`. Missing keys are filled with `default/1` values. MFA tuples are preserved verbatim (not yet applied). ### Note on eager evaluation For literal (non-MFA) values, `pack/1` calls `evaluate/2`, which: - `:headers` — passes through unchanged. - `:parsers` — `Map.merge(default(:parsers), parsers)` (stock parsers are preserved unless explicitly overridden). - `:proxies` — `Enum.map(&RemoteIp.Block.parse!/1)` (raises `ArgumentError` on invalid CIDR). - `:clients` — `Enum.map(&RemoteIp.Block.parse!/1)` (raises `ArgumentError` on invalid CIDR). ### Example — basic packing ```elixir RemoteIp.Options.pack(headers: ~w[x-forwarded-for], proxies: ~w[1.2.0.0/16]) # => [headers: ["x-forwarded-for"], parsers: %{"forwarded" => RemoteIp.Parsers.Forwarded}, # proxies: [%RemoteIp.Block{proto: :v4, net: 16908288, mask: 4294901760}], clients: []] ``` ### Example — MFA kept un-evaluated ```elixir RemoteIp.Options.pack(proxies: {MyApp, :proxies, []}) # => [..., proxies: {MyApp, :proxies, []}, ...] # The MFA is *not* invoked until unpack/1. ``` ``` -------------------------------- ### String.Chars implementation for %RemoteIp.Block{} Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Shows the two clauses of the String.Chars implementation for %RemoteIp.Block{}, producing CIDR strings for IPv4 and IPv6. The prefix is computed by counting the 1-bits in the mask. ```elixir to_string(%RemoteIp.Block{proto: :v4, net: net, mask: mask}) # e.g. "192.168.0.0/24" to_string(%RemoteIp.Block{proto: :v6, net: net, mask: mask}) # e.g. "::/64" ``` -------------------------------- ### call/2 callback implementation Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Implements the Plug.call/2 callback, rewriting conn.remote_ip based on forwarding headers. Sets Logger metadata under :remote_ip and re-evaluates MFA options on every call. ```elixir @impl Plug def call(conn, opts) do debug :ip, [conn] do ip = ip_from(conn.req_headers, opts) || conn.remote_ip add_metadata(ip) %{conn | remote_ip: ip} end end ``` -------------------------------- ### Fetch default headers Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Returns the default headers list. The result is a list of header names. ```elixir RemoteIp.Options.default(:headers) # => ["forwarded", "x-forwarded-for", "x-client-ip", "x-real-ip"] ``` -------------------------------- ### unpack/1 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Evaluates options processed by pack/1, applying MFA tuples as needed. Returns a keyword with fully-evaluated values. ```APIDOC ## `unpack/1` ### Description Evaluates options processed by `pack/1`, applying MFA tuples as needed. Returns a `keyword()` with fully-evaluated values. ### Method `unpack/1` ### Parameters - `options` (keyword()) - Required - Options as produced by `pack/1`. ### Return Value A `keyword()` with fully-evaluated values. Any MFA `{m, f, a}` is applied via `Kernel.apply/3` and the result is then processed by `evaluate/2` (parsers merged with defaults, proxies/clients parsed into `RemoteIp.Block` structs). ### Throws Can raise `ArgumentError` if the return value of an MFA for `:proxies`/`:clients` contains an invalid CIDR string (via `RemoteIp.Block.parse!/1`). See [errors.md](../errors.md). ### Example — evaluating an MFA ```elixir opts = RemoteIp.Options.pack(proxies: {Application, :get_env, [:my_app, :proxies]}) Application.put_env(:my_app, :proxies, ["10.0.0.0/8"]) RemoteIp.Options.unpack(opts) # => [..., proxies: [%RemoteIp.Block{proto: :v4, net: 167772160, mask: 4278190080}], ...] ``` ``` -------------------------------- ### Basic usage in a Plug.Router Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Shows a minimal Plug.Router that plugs RemoteIp without options and responds with the remote IP. ```elixir defmodule MyApp do use Plug.Router plug RemoteIp plug :match plug :dispatch get "/" do send_resp(conn, 200, :inet.ntoa(conn.remote_ip)) end end ``` -------------------------------- ### Configure :remote_ip debug and :logger compile-time purge Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/debugger.md Shows how to enable debug logging for :remote_ip and how :logger's compile_time_purge_matching can strip :debug level messages at compile time, meaning the debug logs will not actually be emitted. ```elixir # All events *would* be logged... config :remote_ip, debug: true # ...But :debug logs will actually get purged at compile time config :logger, compile_time_purge_matching: [[level_lower_than: :info]] ``` -------------------------------- ### Enable RemoteIp.Debugger and view debug logs Source: https://github.com/ajvondrak/remote_ip/blob/main/CONTRIBUTING.md Enable RemoteIp.Debugger to see debug logs for your problematic request, then recompile the dependency. The logs show the headers, parsers, proxies, and clients considered, plus the debugging details for each IP. ```elixir config :remote_ip, debug: true ``` ```console $ mix deps.compile --force remote_ip ``` ```elixir [debug] Processing remote IP headers: ["x-forwarded-for"] parsers: %{"forwarded" => RemoteIp.Parsers.Forwarded} proxies: ["1.2.0.0/16", "2.3.4.5/32"] clients: ["1.2.3.4/32"] [debug] Taking forwarding headers from [{"accept", "*/*"}, {"x-forwarded-for", "1.2.3.4, 10.0.0.1, 2.3.4.5"}] [debug] Parsing IPs from forwarding headers: [{"x-forwarded-for", "1.2.3.4, 10.0.0.1, 2.3.4.5"}] [debug] Parsed IPs from forwarding headers: [{1, 2, 3, 4}, {10, 0, 0, 1}, {2, 3, 4, 5}] [debug] {2, 3, 4, 5} is a known proxy IP [debug] {10, 0, 0, 1} is a reserved IP [debug] {1, 2, 3, 4} is a known client IP [debug] Processed remote IP, found client {1, 2, 3, 4} to replace {127, 0, 0, 1} ``` -------------------------------- ### RemoteIp.from/2 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Documentation for the RemoteIp.from/2 function, which extracts the remote IP from a list of headers without requiring a full Plug.Conn. ```APIDOC ## `from/2` ### Description Extracts the remote IP from a list of headers, without requiring a full `Plug.Conn`. Useful in contexts like `Phoenix.Socket` `connect_info`. ### Function Signature `from(headers, opts \\ [])` ### Parameters - **headers** (`Plug.Conn.headers()`) - Required - A list of `{name, value}` string pairs (header names expected lowercase, as `Plug` normalizes them). - **opts** (`keyword()`) - Optional - Default: `[]` - The same options accepted by `init/1`/the plug. Runtime (MFA) options are evaluated each time the function is called. ### Return Value `:inet.ip_address()` — the resolved client IP as an IP tuple (`{1, 2, 3, 4}` for IPv4, 8-tuple for IPv6) — or `nil` if no client IP could be found in the given headers. ### Side Effects Emits debug log events, but unlike `call/2`, it does *not* set `Logger` metadata. ### Throws Can raise `ArgumentError` if a configured `:proxies` or `:clients` CIDR string is invalid (via `RemoteIp.Block.parse!/1`). See [errors.md](../errors.md). ### Example — basic usage ```elixir x_headers = [{"x-forwarded-for", "1.2.3.4"}] RemoteIp.from(x_headers) # => {1, 2, 3, 4} ``` ### Example — from a Phoenix Socket with options ```elixir defmodule MyApp.MySocket do use Phoenix.Socket @options [ headers: ~w[x-real-ip], proxies: ~w[1.2.0.0/16], clients: ~w[1.2.3.4] ] def connect(params, socket, connect_info) do ip = RemoteIp.from(connect_info[:x_headers], @options) # returns nil when no client is found in the headers case ip do nil -> {:error, :no_ip} ip -> {:ok, socket} end end end ``` ``` -------------------------------- ### Pack options with literals Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Packs headers and proxies with literal values lazily. Proxies are parsed during packing, as shown by the resulting RemoteIp.Block structs. ```elixir RemoteIp.Options.pack(headers: ~w[x-forwarded-for], proxies: ~w[1.2.0.0/16]) # => [headers: ["x-forwarded-for"], parsers: %{"forwarded" => RemoteIp.Parsers.Forwarded}, # proxies: [%RemoteIp.Block{proto: :v4, net: 16908288, mask: 4294901760}], clients: []] ``` -------------------------------- ### RemoteIp.from/2 function definition Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md The function definition for from/2, showing the spec and implementation. It takes a list of headers and options, and returns an IP address tuple or nil. It emits debug log events but does not set Logger metadata. ```elixir @spec from(Plug.Conn.headers(), keyword()) :: :inet.ip_address() | nil def from(headers, opts \\ []) do debug :ip do ip_from(headers, init(opts)) end end ``` -------------------------------- ### Select specific debug events with list config Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/debugger.md Use a list of event atoms to enable only specific debug events. The available events are :options, :headers, :forwarding, :ips, :type, and :ip. ```elixir # Or select specific events (list form): config :remote_ip, debug: [:options, :headers, :forwarding, :ips, :type, :ip] ``` -------------------------------- ### RemoteIp.Options default configuration attributes Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Module-level attributes in `RemoteIp.Options` define the default values for the four supported options: `:headers`, `:parsers`, `:proxies`, and `:clients`. These defaults are referenced during validation and defaulting of configuration for `RemoteIp.init/1` and `RemoteIp.from/2`. ```elixir defmodule RemoteIp.Options do @headers ~w[forwarded x-forwarded-for x-client-ip x-real-ip] @parsers %{"forwarded" => RemoteIp.Parsers.Forwarded} @proxies [] @clients [] end ``` -------------------------------- ### Enable all debug events with boolean config Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/debugger.md Set `config :remote_ip, debug: true` in config/config.exs to enable all debug events. This is equivalent to listing all events explicitly. ```elixir # config/config.exs # All events enabled (boolean form): config :remote_ip, debug: true ``` -------------------------------- ### default/1 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Returns the default value for a given option. Supported options are :headers, :parsers, :proxies, and :clients. ```APIDOC ## `default/1` ### Description Returns the default value for the given option. Supported options are `:headers`, `:parsers`, `:proxies`, and `:clients`. ### Method `default/1` ### Parameters - `option` (atom()) - Required - One of `:headers`, `:parsers`, `:proxies`, `:clients`. ### Return Value - `default(:headers)` → `~w[forwarded x-forwarded-for x-client-ip x-real-ip]` - `default(:parsers)` → `%{"forwarded" => RemoteIp.Parsers.Forwarded}` - `default(:proxies)` → `[]` - `default(:clients)` → `[]` ### Throws A `FunctionClauseError` if given any atom other than the four supported option names (no catch-all clause). ### Example — basic ```elixir RemoteIp.Options.default(:headers) # => ["forwarded", "x-forwarded-for", "x-client-ip", "x-real-ip"] ``` ### Example — merge default parsers before adding a custom one ```elixir parsers = Map.merge(RemoteIp.Options.default(:parsers), %{"x-special" => SpecialParser}) ``` ``` -------------------------------- ### Callback definition for RemoteIp.Parser.parse/1 Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parser.md Defines the parse/1 callback that takes a header binary and returns a list of IP address tuples. ```elixir @callback parse(header :: binary()) :: [:inet.ip_address()] ``` -------------------------------- ### Desired IP list from X-Forwarded-For Source: https://github.com/ajvondrak/remote_ip/blob/main/extras/algorithm.md Shows the desired parsed IP list from the X-Forwarded-For header, preserving the order of the proxy chain. ```elixir # This is what we want [{1, 2, 3, 4}, {1, 1, 1, 1}] ``` -------------------------------- ### parse/1 callback implementation Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parsers_forwarded.md The RemoteIp.Parser callback implementation. Parses the header using Combine and returns a flat list of IP tuples from all 'for=' parameters. Returns [] for malformed input. ```elixir @impl RemoteIp.Parser def parse(header) do case Combine.parse(header, forwarded()) do [elements] -> Enum.flat_map(elements, &parse_forwarded_for/1) _ -> [] end end ``` -------------------------------- ### Configure remote_ip with debug: true Source: https://github.com/ajvondrak/remote_ip/blob/main/integration/tests/debug/README.md Sets the debug option to true for the remote_ip library, enabling debug logging. This configuration is used in the test app to compile remote_ip with debug messages. ```elixir config :remote_ip, debug: true ``` -------------------------------- ### Configure Logger metadata for remote_ip Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/configuration.md Configures Logger to include the :remote_ip metadata in log messages. RemoteIp.call/2 populates this metadata, but RemoteIp.from/2 does not. ```elixir # config/config.exs config :logger, message: "$metadata[$level] $message\n", metadata: [:remote_ip] ``` -------------------------------- ### Multiple elements and bracketed IPv6 with port Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/parsers_forwarded.md Parses multiple forwarded elements, including bracketed IPv6 addresses with ports. ```elixir RemoteIp.Parsers.Forwarded.parse("for=\"[::1]\", for=\"[::2]:8080\"") # => [{0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 2}] ``` -------------------------------- ### Define default/1 clauses for valid options Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Defines the default/1 function with clauses for the four supported option names: :headers, :parsers, :proxies, and :clients. This is part of the RemoteIp.Options module API. ```elixir def default(option) def default(:headers), do: @headers def default(:parsers), do: @parsers def default(:proxies), do: @proxies def default(:clients), do: @clients ``` -------------------------------- ### Unpack options to evaluate MFAs Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Evaluates options produced by pack/1. For each option, if the stored value is an MFA tuple, it calls evaluate/2 on the result; otherwise it returns the value directly. ```elixir def unpack(options) do [ headers: unpack(options, :headers), parsers: unpack(options, :parsers), proxies: unpack(options, :proxies), clients: unpack(options, :clients) ] end ``` -------------------------------- ### Plug RemoteIp into a Plug.Router pipeline Source: https://github.com/ajvondrak/remote_ip/blob/main/README.md Adds the RemoteIp plug to a Plug.Router module's pipeline. Place it before the :match and :dispatch plugs to rewrite the remote_ip based on forwarding headers. ```elixir defmodule MyApp do use Plug.Router plug RemoteIp plug :match plug :dispatch # get "/" do ... end ``` -------------------------------- ### Module definition for RemoteIp Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/remote_ip.md Defines the RemoteIp module, importing RemoteIp.Debugger and declaring the Plug behaviour. ```elixir defmodule RemoteIp do import RemoteIp.Debugger @behaviour Plug end ``` -------------------------------- ### Undesired header list (reversed order) Source: https://github.com/ajvondrak/remote_ip/blob/main/extras/algorithm.md Shows the reversed header order that is NOT desired, as it would break the proxy chain interpretation. ```elixir # This is NOT what we want [{"forwarded", "for=2.2.2.2"}, {"x-forwarded-for", "1.2.3.4, 1.1.1.1"}] ``` -------------------------------- ### Recompile remote_ip after changing debug config Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/debugger.md Run these commands to recompile the :remote_ip dependency after changing the debug configuration, since debugging is resolved at compile time. ```console $ mix deps.clean --build remote_ip $ mix deps.compile ``` -------------------------------- ### Enable compile-time debug events Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/configuration.md Enables compile-time debug events for the :remote_ip library. Because the setting is compile-time, the dependency must be recompiled after changing it. ```elixir # config/config.exs config :remote_ip, debug: true ``` ```console $ mix deps.clean --build remote_ip $ mix deps.compile ``` -------------------------------- ### __message__/2 function clauses Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/debugger.md Shows the multiple clauses of __message__/2, each handling a different debug event identifier. The comments describe the message content for each event. ```elixir def __message__(:options, [], options) # multi-line summary of headers/parsers/proxies/clients def __message__(:headers, [], headers) # "Taking forwarding headers from ..." def __message__(:forwarding, [], headers) # "Parsing IPs from forwarding headers: ..." def __message__(:ips, [], ips) # "Parsed IPs from forwarding headers: ..." def __message__(:type, [ip], type) # "{ip} is a known client/proxy/reserved/unknown IP" def __message__(:ip, [old_conn], new_conn) # "Processed remote IP, found client ... to replace ..." def __message__(:ip, [], ip) # "Processed remote IP, no client found" or "found client ..." ``` -------------------------------- ### Undesired IP list (reversed order) Source: https://github.com/ajvondrak/remote_ip/blob/main/extras/algorithm.md Shows the reversed IP list that is NOT desired, as it would misrepresent the proxy chain. ```elixir # This is NOT what we want [{1, 1, 1, 1}, {1, 2, 3, 4}] ``` -------------------------------- ### parse!/1 implementation Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Parses a CIDR string, raising ArgumentError on error. Error messages are of the form "Invalid address ... in CIDR ..." or "Invalid prefix ... in CIDR ...". ```elixir def parse!(cidr) do case parse(cidr) do {:ok, block} -> block {:error, message} -> raise ArgumentError, message end end ``` -------------------------------- ### Compile-time debug configuration logic Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/debugger.md This code reads the debug configuration at compile time and defines a private function to check if a given event is enabled. It handles both list and boolean forms of the config. ```elixir @debug Application.compile_env(:remote_ip, :debug, false) cond do is_list(@debug) -> defp debug?(id), do: Enum.member?(@debug, id) is_boolean(@debug) -> defp debug?(_), do: @debug end ``` -------------------------------- ### RemoteIp.Block struct definition Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/block.md Defines the RemoteIp.Block struct with fields :proto, :net, and :mask. Used internally by RemoteIp.Options and RemoteIp. ```elixir defstruct [:proto, :net, :mask] ``` -------------------------------- ### Pack MFA tuple unevaluated Source: https://github.com/ajvondrak/remote_ip/blob/main/_autodocs/api-reference/options.md Packs options containing an MFA tuple, which is preserved as-is during packing. The MFA is applied only when unpack/1 is called. ```elixir RemoteIp.Options.pack(proxies: {MyApp, :proxies, []}) # => [..., proxies: {MyApp, :proxies, []}, ...] # The MFA is *not* invoked until unpack/1. ```