Socket Address v0.2.0 SocketAddress
Defines an Internet socket address.
The SocketAddress struct contains the fields ip
(stored as a tuple) and
port
, which can be accessed directly:
iex> {:ok, socket_address} = SocketAddress.new("127.0.0.1", 80)
iex> socket_address
#SocketAddress<127.0.0.1:80>
iex> socket_address.ip
{127, 0, 0, 1}
iex> socket_address.port
80
Summary
Functions
Creates a new socket address with the given ip
and port
Converts a socket address to an options keyword list
Types
The IP address of a socket
The socket address type
Functions
Creates a new socket address with the given ip
and port
.
Returns {:ok, socket_address}
if the IP address and port number are valid,
returns {:error, reason}
otherwise. A valid IP address is an IPv4 or IPv6
address that can be parsed by :inet.parse_address/1
, and a valid port must
be an integer in the range of 0..65535
.
Examples
iex> {:ok, socket_address} = SocketAddress.new("127.0.0.1", 80)
iex> socket_address
#SocketAddress<127.0.0.1:80>
iex> {:ok, socket_address} = SocketAddress.new('127.0.0.1', 80)
iex> socket_address
#SocketAddress<127.0.0.1:80>
iex> {:ok, socket_address} = SocketAddress.new({127, 0, 0, 1}, 80)
iex> socket_address
#SocketAddress<127.0.0.1:80>
iex> {:ok, socket_address} = SocketAddress.new("fe80::204:acff:fe17:bf38", 80)
iex> socket_address
#SocketAddress<[FE80::204:ACFF:FE17:BF38]:80>
iex> SocketAddress.new("100.200.300.400", 80)
{:error, :invalid_ip}
iex> SocketAddress.new("0.0.0.0", 99999)
{:error, :invalid_port}
Converts a socket address to an options keyword list.
Returns a keyword list of the socket address ip
and port
fields merged
with any provided opts
. All keys, including duplicated keys, given in
opts
will be added to the socket address fields, overriding any existing
one.
Examples
iex> {:ok, socket_address} = SocketAddress.new("127.0.0.1", 80)
iex> SocketAddress.to_opts(socket_address)
[ip: {127, 0, 0, 1}, port: 80]
iex> {:ok, socket_address} = SocketAddress.new("127.0.0.1", 80)
iex> SocketAddress.to_opts(socket_address, [compress: true])
[ip: {127, 0, 0, 1}, port: 80, compress: true]
iex> {:ok, socket_address} = SocketAddress.new("127.0.0.1", 80)
iex> SocketAddress.to_opts(socket_address, [port: 8888])
[ip: {127, 0, 0, 1}, port: 8888]