API reference › @evolu/common › Type › IpAddressFromString
const IpAddressFromString: transform(
"IpAddressFromString",
String,
IpAddress,
{
from: (value: string): Result<IpAddress, IpAddressFromStringError> => {
const address = value.includes(":")
? canonicalizeIpv6Address(value)
: Ipv4Address.is(value)
? value
: undefined;
return address === undefined
? err({ type: "IpAddressFromString", value })
: ok(address as IpAddress);
},
to: (value: IpAddress) => value,
},
formatIpAddressFromStringError,
);
Defined in: packages/common/src/Type.ts:9553
Transforms IP address text into an IpAddress.
Text containing a colon is parsed as IPv6 text, as
Ipv6AddressFromString parses it, and converted to its canonical
Ipv6Address. Other text must be an Ipv4Address, which has one
spelling. Because a colon selects IPv6, an IPv4 address with a port, such as
1.2.3.4:80, is rejected as invalid IPv6 text.
Encoding returns the canonical text, not the original spelling.
Example
import {
assertEqual,
assertErr,
assertOk,
IpAddressFromString,
} from "@evolu/common";
assertOk(IpAddressFromString.fromUnknown("192.168.1.1"), "192.168.1.1");
assertOk(IpAddressFromString.fromUnknown("2001:0DB8::1"), "2001:db8::1");
const invalid = IpAddressFromString.fromUnknown("1.2.3.4:80");
assertErr(invalid, { type: "IpAddressFromString", value: "1.2.3.4:80" });
assertEqual(
IpAddressFromString.formatError(invalid.error),
'The value "1.2.3.4:80" is not a valid IP address.',
);