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

Types

The IP address of a socket

The port number of a socket

t()

The socket address type

Functions

Creates a new socket address with the given ip and port

Converts a socket address to an options keyword list

Types

ip_address()
ip_address() :: String.t | charlist | :inet.ip_address

The IP address of a socket

port_number()
port_number() :: 0..65535

The port number of a socket

t()
t() :: %SocketAddress{ip: :inet.ip_address, port: port_number}

The socket address type

Functions

new(ip, port)
new(ip_address, port_number) ::
  {:ok, t} |
  {:error, :invalid_ip | :invalid_port}

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}
to_opts(socket_address, opts \\ [])
to_opts(t, Keyword.t) :: Keyword.t

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]