Skip to content

Commit

Permalink
add Ipaddr of_octet functions
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanGibb committed Mar 30, 2023
1 parent 3c8d00a commit 2e93b07
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/ipaddr.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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))))

Expand Down
13 changes: 13 additions & 0 deletions lib/ipaddr.mli
Original file line number Diff line number Diff line change
Expand Up @@ -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. *)
Expand Down

0 comments on commit 2e93b07

Please sign in to comment.