MCPcopy Create free account
hub / github.com/Effect-TS/effect / inetAddressFromString

Function inetAddressFromString

packages/effect/src/net/NetAddress.ts:1934–1980  ·  view source on GitHub ↗
(input: string)

Source from the content-addressed store, hash-verified

1932 * @since 4.0.0
1933 */
1934export const inetAddressFromString = (input: string): Result.Result<InetAddress, NetAddressError> => {
1935 let host: string
1936 let portText: string
1937 let scopeId = 0
1938 const bracketed = input.startsWith("[")
1939 if (bracketed) {
1940 const end = input.indexOf("]")
1941 if (end < 0 || input[end + 1] !== ":" || input.indexOf("]", end + 1) !== -1) {
1942 return addressError(input, "expected [IPv6]:port")
1943 }
1944 host = input.slice(1, end)
1945 portText = input.slice(end + 2)
1946 const scopeSeparator = host.indexOf("%")
1947 if (scopeSeparator !== -1) {
1948 const scopeText = host.slice(scopeSeparator + 1)
1949 if (host.indexOf("%", scopeSeparator + 1) !== -1 || !/^\d+$/.test(scopeText)) {
1950 return addressError(input, "scope identifier must be decimal")
1951 }
1952 scopeId = Number(scopeText)
1953 if (!Number.isInteger(scopeId) || scopeId > 0xffffffff) {
1954 return addressError(input, "scope identifier must be an unsigned 32-bit integer")
1955 }
1956 host = host.slice(0, scopeSeparator)
1957 }
1958 } else {
1959 const separator = input.lastIndexOf(":")
1960 if (separator < 0) {
1961 return addressError(input, "expected host:port or [IPv6]:port")
1962 }
1963 if (input.indexOf(":") !== separator) {
1964 return addressError(input, "IPv6 addresses must be bracketed")
1965 }
1966 host = input.slice(0, separator)
1967 portText = input.slice(separator + 1)
1968 }
1969 if (!/^(0|[1-9]\d*)$/.test(portText)) {
1970 return addressError(input, "port must be an unpadded decimal integer")
1971 }
1972 return Result.flatMap(ipFromString(host), (address): Result.Result<InetAddress, NetAddressError> => {
1973 if (bracketed !== isIpv6Address(address)) {
1974 return addressError(input, "only IPv6 addresses use brackets")
1975 }
1976 return isIpv6Address(address)
1977 ? inetAddressV6(address, Number(portText), { scopeId })
1978 : inetAddressV4(address, Number(portText))
1979 })
1980}
1981
1982/**
1983 * Parses a trusted numeric internet address and port, throwing on failure.

Callers 3

inetAddressFromInputFunction · 0.85

Calls 7

addressErrorFunction · 0.85
ipFromStringFunction · 0.85
isIpv6AddressFunction · 0.85
inetAddressV6Function · 0.85
inetAddressV4Function · 0.85
sliceMethod · 0.80
NumberFunction · 0.50

Tested by

no test coverage detected