forked from elcritch/ExDhcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhcp.ex
69 lines (54 loc) · 1.52 KB
/
dhcp.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
defmodule Mix.Tasks.Dhcp do
use Mix.Task
require Logger
alias ExDhcp.Packet
@moduledoc """
A tool for sending a saved DHCP packet (usually saved from `mix snoop`) to a DHCP server
## Usage
```
mix dhcp <filename> [options]
```
## Options
- `--bind <device>` or `-b <device>` binds this mix task to a specific
network device.
- `--save <filename>` or `-s <filename>` saves the response packet (as erlang term binaries) to files
with the given prefix
- `!` fire and forget, don't wait for the response.
"""
@shortdoc "send a saved DHCP packet"
def run([filename | params]) do
params = parse_params(params)
response = filename
|> File.read!
|> :erlang.binary_to_term
|> Packet.send(params)
unless params[:nowait] do
savemsg = save(response, params)
Logger.info(savemsg <> inspect response)
end
:ok
end
defp save(response, params) do
path = params[:save]
if path do
File.write!(path, :erlang.term_to_binary(response))
"(saved to #{path})"
else
""
end
end
@bind ~w(-b --bind)
@save ~w(-s --save)
@nowait "!"
defp parse_params([]), do: []
defp parse_params([switch, bind | rest]) when switch in @bind do
[bind: bind] ++ parse_params(rest)
end
defp parse_params([switch, filename | rest]) when switch in @save do
[save: filename] ++ parse_params(rest)
end
defp parse_params([@nowait | rest]) do
[nowait: true] ++ parse_params(rest)
end
defp parse_params([_ | rest]), do: parse_params(rest)
end