Use only Qemu Kill on the teardown of double qemu setup
[csit.git] / resources / traffic_scripts / send_tcp_udp.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 an TCP or UDP packet
16 from one interface to the other.
17 """
18
19 import sys
20 import ipaddress
21
22 from scapy.layers.inet import IP, UDP, TCP
23 from scapy.layers.inet6 import IPv6
24 from scapy.all import Ether
25
26 from resources.libraries.python.PacketVerifier import RxQueue, TxQueue
27 from resources.libraries.python.TrafficScriptArg import TrafficScriptArg
28
29
30 def valid_ipv4(ip):
31     """Check if IP address has the correct IPv4 address format.
32
33     :param ip: IP address.
34     :type ip: str
35     :return: True in case of correct IPv4 address format,
36              otherwise return False.
37     :rtype: bool
38     """
39     try:
40         ipaddress.IPv4Address(unicode(ip))
41         return True
42     except (AttributeError, ipaddress.AddressValueError):
43         return False
44
45
46 def valid_ipv6(ip):
47     """Check if IP address has the correct IPv6 address format.
48
49     :param ip: IP address.
50     :type ip: str
51     :return: True in case of correct IPv6 address format,
52              otherwise return False.
53     :rtype: bool
54     """
55     try:
56         ipaddress.IPv6Address(unicode(ip))
57         return True
58     except (AttributeError, ipaddress.AddressValueError):
59         return False
60
61
62 def main():
63     """Send TCP or UDP packet from one traffic generator interface to the other.
64     """
65     args = TrafficScriptArg(
66         ['tx_mac', 'rx_mac', 'src_ip', 'dst_ip', 'protocol',
67          'source_port', 'destination_port'])
68
69     src_mac = args.get_arg('tx_mac')
70     dst_mac = args.get_arg('rx_mac')
71     src_ip = args.get_arg('src_ip')
72     dst_ip = args.get_arg('dst_ip')
73     tx_if = args.get_arg('tx_if')
74     rx_if = args.get_arg('rx_if')
75
76     protocol = args.get_arg('protocol')
77     source_port = args.get_arg('source_port')
78     destination_port = args.get_arg('destination_port')
79
80     ip_version = None
81     if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
82         ip_version = IP
83     elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
84         ip_version = IPv6
85     else:
86         ValueError("Invalid IP version!")
87
88     if protocol.upper() == 'TCP':
89         protocol = TCP
90     elif protocol.upper() == 'UDP':
91         protocol = UDP
92     else:
93         raise ValueError("Invalid type of protocol!")
94
95     rxq = RxQueue(rx_if)
96     txq = TxQueue(tx_if)
97
98     pkt_raw = (Ether(src=src_mac, dst=dst_mac) /
99                ip_version(src=src_ip, dst=dst_ip) /
100                protocol(sport=int(source_port), dport=int(destination_port)))
101
102     txq.send(pkt_raw)
103     ether = rxq.recv(2)
104
105     if ether is None:
106         raise RuntimeError("TCP/UDP Rx timeout")
107
108     if 'TCP' in ether:
109         print ("TCP packet received.")
110
111     elif 'UDP' in ether:
112         print ("UDP packet received.")
113     else:
114         raise RuntimeError("Not an TCP or UDP packet received {0}"
115                            .format(ether.__repr__()))
116
117     sys.exit(0)
118
119
120 if __name__ == "__main__":
121     main()