diff --git a/lib/ipaddr.ml b/lib/ipaddr.ml index 84afa37..70805f4 100644 --- a/lib/ipaddr.ml +++ b/lib/ipaddr.ml @@ -1137,6 +1137,15 @@ let with_port_of_string ~default s = Ok (ipv6, default)) with Parse_error (msg, _) -> Error (`Msg ("Ipaddr: " ^ msg)) +let of_octets_exn bs = + match String.length bs with + | 4 -> V4 (V4.of_octets_exn bs) + | 16 -> V6 (V6.of_octets_exn bs) + | _ -> raise (Parse_error ("octets must be of length 4 or 16", bs)) + +let of_octets bs = try_with_result of_octets_exn bs +let to_octets i = match i with V4 p -> V4.to_octets p | V6 p -> V6.to_octets p + let v6_of_v4 v4 = V6.(Prefix.(network_address ipv4_mapped (of_int32 (0l, 0l, 0l, v4)))) diff --git a/lib/ipaddr.mli b/lib/ipaddr.mli index 3172ae9..d1f088f 100644 --- a/lib/ipaddr.mli +++ b/lib/ipaddr.mli @@ -638,6 +638,19 @@ val with_port_of_string : - [::1:8080] returns the IPv6 [::1:8080] with the [default] port - [0:0:0:0:0:0:0:1:8080] returns [::1] with the port [8080]. *) +val of_octets_exn : string -> t +(** [of_octets_exn octets] is the address {!t} represented by [octets]. The + [octets] must be 4 bytes long for a {!V4} or 16 if a {!V6}. Raises + {!Parse_error} if [octets] is not a valid representation of an address. *) + +val of_octets : string -> (t, [> `Msg of string ]) result +(** Same as {!of_octets_exn} but returns a result type instead of raising an + exception. *) + +val to_octets : t -> string +(** [to_octets addr] returns the bytes representing the [addr] octets, which + will be 4 bytes long if addr is a {!V4} or 16 if a {!V6}. *) + val v4_of_v6 : V6.t -> V4.t option (** [v4_of_v6 ipv6] is the IPv4 representation of the IPv6 address [ipv6]. If [ipv6] is not an IPv4-mapped address, None is returned. *)