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:
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 """Traffic script that sends an TCP or UDP packet
16 from one interface to the other.
22 from scapy.all import Ether
23 from scapy.layers.inet import IP, UDP, TCP
24 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS
26 from resources.libraries.python.PacketVerifier import RxQueue, TxQueue
27 from resources.libraries.python.TrafficScriptArg import TrafficScriptArg
31 """Check if IP address has the correct IPv4 address format.
33 :param ip: IP address.
35 :return: True in case of correct IPv4 address format,
36 otherwise return False.
40 ipaddress.IPv4Address(unicode(ip))
42 except (AttributeError, ipaddress.AddressValueError):
47 """Check if IP address has the correct IPv6 address format.
49 :param ip: IP address.
51 :return: True in case of correct IPv6 address format,
52 otherwise return False.
56 ipaddress.IPv6Address(unicode(ip))
58 except (AttributeError, ipaddress.AddressValueError):
63 """Send TCP or UDP packet from one traffic generator interface to the other.
65 args = TrafficScriptArg(['tx_mac', 'rx_mac', 'src_ip', 'dst_ip', 'protocol',
66 'source_port', 'destination_port'])
68 src_mac = args.get_arg('tx_mac')
69 dst_mac = args.get_arg('rx_mac')
70 src_ip = args.get_arg('src_ip')
71 dst_ip = args.get_arg('dst_ip')
72 tx_if = args.get_arg('tx_if')
73 rx_if = args.get_arg('rx_if')
75 protocol = args.get_arg('protocol')
76 source_port = args.get_arg('source_port')
77 destination_port = args.get_arg('destination_port')
79 if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
81 elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
84 ValueError("Invalid IP version!")
86 if protocol.upper() == 'TCP':
88 elif protocol.upper() == 'UDP':
91 raise ValueError("Invalid protocol type!")
96 pkt_raw = (Ether(src=src_mac, dst=dst_mac) /
97 ip_version(src=src_ip, dst=dst_ip) /
98 protocol(sport=int(source_port), dport=int(destination_port)))
105 raise RuntimeError('TCP/UDP Rx timeout')
107 if ether.haslayer(ICMPv6ND_NS):
108 # read another packet in the queue if the current one is ICMPv6ND_NS
111 # otherwise process the current packet
115 print ("TCP packet received.")
118 print ("UDP packet received.")
120 raise RuntimeError("Not an TCP or UDP packet received {0}".
121 format(ether.__repr__()))
126 if __name__ == "__main__":