1715bb1d01dc7b533b5cb5f54d14f9a37021f6a2
[csit.git] / resources / traffic_scripts / dhcp / send_dhcp_discover.py
1 #!/usr/bin/env python
2 # Copyright (c) 2016 Cisco and/or its affiliates.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """Traffic script that sends DHCP DISCOVER packets."""
16
17 import sys
18
19 from scapy.all import Ether
20 from scapy.layers.inet import IP, UDP
21 from scapy.layers.inet import UDP_SERVICES
22 from scapy.layers.dhcp import DHCP, BOOTP
23
24 from resources.libraries.python.PacketVerifier import RxQueue, TxQueue
25 from resources.libraries.python.TrafficScriptArg import TrafficScriptArg
26
27
28 def main():
29     """Send DHCP DISCOVER packet."""
30
31     args = TrafficScriptArg(['tx_src_ip', 'tx_dst_ip'])
32
33     tx_if = args.get_arg('tx_if')
34     rx_if = args.get_arg('rx_if')
35
36     rxq = RxQueue(rx_if)
37     txq = TxQueue(tx_if)
38
39     tx_src_ip = args.get_arg('tx_src_ip')
40     tx_dst_ip = args.get_arg('tx_dst_ip')
41
42     sent_packets = []
43
44     dhcp_discover = Ether(dst="ff:ff:ff:ff:ff:ff") / \
45                     IP(src=tx_src_ip, dst=tx_dst_ip) / \
46                     UDP(sport=68, dport=67) / \
47                     BOOTP(op=1,) / \
48                     DHCP(options=[("message-type", "discover"),
49                                   "end"])
50
51     sent_packets.append(dhcp_discover)
52     txq.send(dhcp_discover)
53
54     ether = rxq.recv(2)
55
56     if ether is None:
57         raise RuntimeError('DHCP DISCOVER timeout')
58
59     if ether[UDP].dport != UDP_SERVICES.bootps:
60         raise RuntimeError("UDP destination port error.")
61     print "UDP destination port: OK."
62
63     if ether[UDP].sport != UDP_SERVICES.bootpc:
64         raise RuntimeError("UDP source port error.")
65     print "UDP source port: OK."
66
67     if ether[DHCP].options[0][1] != 1:  # 1 - DISCOVER message
68         raise RuntimeError("DHCP DISCOVER message error.")
69     print "DHCP DISCOVER message OK."
70
71     sys.exit(0)
72
73 if __name__ == "__main__":
74     main()