Best Python code snippet using tempest_python
client.py
Source:client.py
1import socket2import sys3import time 4from struct import *5import threading 6from threading import Thread7from SocketServer import ThreadingMixIn8class sendthread(Thread):9 def __init__(self):10 Thread.__init__(self)11 12 print "New thread started"13 def run(self):14 print "entering 1"15 16def sendack(stcp_seq):17 global UDP_IP18 global receiverport19 global ackmark20 global source_ip21 global dest_ip 22 global tcp_source23 global tcp_dest 24 global tcp_seq25 global tcp_ack_seq26 global tcp_doff27 global tcp_fin28 global tcp_syn29 global tcp_rst30 global tcp_psh31 global tcp_ack32 global tcp_urg33 global tcp_window34 global tcp_check35 global tcp_urg_ptr 36 global tcp_offset_res37 global tcp_flags38 print "Sending ack for chunk" , stcp_seq39 tcp_seq = stcp_seq + 140 tcp_ack = 141 tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5)42 ackpacket = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr)43 #time.sleep(3.0)44 sock.sendto(ackpacket, (UDP_IP, UDP_PORT))45 46class receivethread(Thread):47 def __init__(self):48 Thread.__init__(self)49 print "New thread started"50 51 def run(self):52 global UDP_IP53 global receiverport54 global ackmark55 global source_ip56 global dest_ip 57 global tcp_source58 global tcp_dest 59 global tcp_seq60 global tcp_ack_seq61 global tcp_doff62 global tcp_fin63 global tcp_syn64 global tcp_rst65 global tcp_psh66 global tcp_ack67 global tcp_urg68 global tcp_window69 global tcp_check70 global tcp_urg_ptr 71 global tcp_offset_res72 global tcp_flags73 global packetsize74 global pktdata75 global filename76 global winsize77 global receiveddata78 receiveddata = {}79 stopflag = 080 seqwindow = []81 rcvdict = {}82 pktdict = {}83 sock.settimeout(60.0)84 85 file = open(filename, 'w+')86 87 print "entering"88 89 90 packetsize = 57091 k=192 for i in range (1,winsize+1):93 seqwindow.append(k)94 k = k + packetsize95 expectedseq = seqwindow[winsize-1]96 for t in seqwindow:97 rcvdict[t] = 098 99 while True:100 101 try:102 packet, addr = sock.recvfrom(2048)103 rcvtime = time.time()104 tcp_check = 0105 tcp_header = packet[:20]106 message = packet[20:]107 #print tcp_header108 #print message 109 110 111 stcp_source, stcp_dest, stcp_seq, stcp_ack_seq, stcp_offset_res, stcp_flags, stcp_window, stcp_check, stcp_urg_ptr = unpack('!HHLLBBHHH',tcp_header)112 clienttcp_header = pack('!HHLLBBHHH' , stcp_source, stcp_dest, stcp_seq, stcp_ack_seq, stcp_offset_res, stcp_flags, stcp_window, tcp_check, stcp_urg_ptr)113 psh = clienttcp_header + message 114 clienttcp_check = checksum(psh)115 pktdata[stcp_seq] = packet116 receiveddata[stcp_seq] = rcvtime117 118 # print "received tcp_check is ", stcp_check119 #print "client tcp_check" , clienttcp_check 120 121 122 # print "chunk checksum received:", i ,stcp_check123 #print evaluateflag(stcp_flags)124 if evaluateflag(stcp_flags) == "data" and stcp_seq in seqwindow:125 126 if clienttcp_check == stcp_check:127 print "checksums match"128 if seqwindow[0] == stcp_seq: #if first element of window has been acked , let us change the window 129 pktdict[stcp_seq] = message 130 rcvdict[seqwindow[0]] = 1 131 j=0132 i=1133 while i < winsize and rcvdict[seqwindow[i]]==1:134 i= i+1135 136 k=0137 while k < i:138 item = pktdata[seqwindow[k]]139 file.write(item[20:]) 140 writelog(item,seqwindow[k])141 k=k+1142 143 while i < winsize: 144 seqwindow[j] = seqwindow[i]145 j = j+1146 i = i + 1147 # acknext = seqwindow[i-1]148 # print "acknext is" , acknext149 150 while j < winsize:151 seqwindow[j] = expectedseq + packetsize 152 rcvdict[seqwindow[j]] = 0153 expectedseq = expectedseq + packetsize154 j = j+1155 156 else:157 rcvdict[stcp_seq] = 1 #1 indicates packet is received158 pktdict[stcp_seq] = message159 160 acknum = stcp_seq - 1 + packetsize161 print "Seqwindow after receiving packet " , stcp_seq , "is " ,seqwindow162 sendack(acknum)163 else:164 print "checksums don't match"165 continue166 167 168 elif evaluateflag(stcp_flags) == "FIN":169 print "connection is going to be terminated , sending FIN ACK"170 tcp_seq = stcp_seq + 1171 tcp_ack = 1172 tcp_fin = 1173 tcp_syn = 0174 tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5)175 finackpacket = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr)176 sock.sendto(finackpacket, (UDP_IP, UDP_PORT))177 sock.close() 178 sys.exit()179 except socket.error:180 print "socket error"181 182 183def writelog(packet,seqnum):184 global pktdata185 global receiveddata186 packet = pktdata[seqnum]187 tcpheader = packet[:20]188 tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr = unpack('!HHLLBBHHH',tcpheader)189 packettype = "DATA "190 writemsg = "Packet Type: " + packettype + "Timestamp: " + str(receiveddata[seqnum]) + "\n"191 192 acktcp_seq = tcp_seq + 1193 writemsg = writemsg + " seq number of packet received: " + str(tcp_seq) + "\n"194 writemsg = writemsg + "header details: " + "\n"195 196 writemsg = writemsg + " source: " + str(tcp_source) + " "197 writemsg = writemsg + " destination: " + str(tcp_dest) + " " + "FLAGS: " + str(tcp_flags) + " " + "windowsize: " + str(tcp_window) + " " + "checksum: " + str(tcp_check) + "\n"198 log.write(writemsg)199 writemsg = writemsg + " Sending ack details: " + " ack sequence number: " + str(tcp_seq+1) + "\n"200 201 if filename != "stdout":202 log.write(writemsg)203 log.write("\n\n")204 elif filename=="stdout":205 sys.stdout.write(writemsg + "\n\n")206 207""" 208def writelogsyn(packet,packettype):209 210 tcpheader = packet[:20]211 tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr = unpack('!HHLLBBHHH',tcpheader)212 packettype = packettype213 if tcp_seq in rttdata:214 writemsg = "Packet Type: " + packettype + "Timestamp: " + " "+ "\n"215 else:216 writemsg = "Packet Type: " + packettype + "\n"217 218 log.write(writemsg)219 acktcp_seq = tcp_seq + 1220 writemsg = "seq number of packet sent: " + str(tcp_seq) + "\n" 221 writemsg = writemsg + "header details: " + "\n"222 log.write(writemsg)223 writemsg = "source: " + str(tcp_source) + " "224 writemsg = writemsg + " destination: " + str(tcp_dest) + " " + "FLAGS: " + str(tcp_flags) + " " + "windowsize: " + str(tcp_window) + " " + "checksum: " + str(tcp_check) + "\n"225 log.write(writemsg)226 writemsg = "Sent ack: " + " ack sequence number: " + str(tcp_seq + 1) + "\n"227 log.write(writemsg)228 log.write("\n\n") 229""" 230 231 232 233 234def checksum(data):235 s = 0236 237 if len(data)%2==1:238 data = data + "\0" #padding239 240 # loop taking 2 characters at a time241 for i in range(0, len(data), 2):242 w = ord(data[i]) + (ord(data[i+1]) << 8 )243 244 s = s + w245 246 247 s = (s>>16) + (s & 0xffff);248 249 s = s + (s >> 16);250 251 #complement and mask to 4 byte short252 s = ~s & 0xffff253 254 255 return s256def evaluateflag(flags):257 num = 6258 bits = [(flags >> bit) & 1 for bit in range(num -1, -1 , -1)]259 260 for position,bit in enumerate(bits):261 if position == 1 and bit == 1:262 return "ACK"263 if position == 5 and bit == 1:264 print "FIN pack"265 return "FIN" 266 return "data" 267 268 269 270 271 272global UDP_IP273UDP_IP = sys.argv[3]#"127.0.0.1"274global server_ip275server_ip = "192.168.73.1"276global UDP_PORT277UDP_PORT = int(sys.argv[4])#5005278global receiverport 279receiverport = int(sys.argv[2])#5000280global pktdata281pktdata={}282global receiveddata283receiveddata = {}284print "UDP target IP:", UDP_IP285print "UDP target port:", UDP_PORT286 287# tcp header fields288global tcp_source289tcp_source = receiverport # source port290global tcp_dest291tcp_dest = UDP_PORT # destination port292global tcp_Seq293tcp_seq = 0294global tcp_ack_seq295tcp_ack_seq = 0296global tcp_doff297tcp_doff = 5 #4 bit field, size of tcp header, 5 * 4 = 20 bytes298#tcp flags299global tcp_fin300tcp_fin = 0301global tcp_syn302tcp_syn = 1303global tcp_rst304tcp_rst = 0305global tcp_psh306tcp_psh = 0307global tcp_Ack308tcp_ack = 0309global tcp_urg310tcp_urg = 0311global tcp_window312tcp_window = 3 # maximum allowed window size313global tcp_check314tcp_check = 0315global tcp_urg_ptr316tcp_urg_ptr = 0317global tcp_offset318global filename319filename = sys.argv[1]320global winsize321 322tcp_offset_res = (tcp_doff << 4) + 0323tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5)324i = 0325sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)326sock.bind((UDP_IP, int(receiverport))) 327sock.settimeout(5.0) # Timeout in case SYN,ACK gets lost328while True:329 SYNpacket = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr)330 try:331 sock.sendto(SYNpacket, (UDP_IP, UDP_PORT))332 print "SYN to server " , tcp_flags333 except socket.error:334 print "not able to connect , trying again after", 1 << i , "seconds"335 if i <= 5:336 time.sleep(1 << i)337 i=i+1338 continue339 else:340 print "error , not able to eastablish connection"341 break 342 try:343 synack, addr = sock.recvfrom(2048)344 header = synack[:20]345 346 except socket.timeout:347 print " syn ack not received yet , sending syn again" 348 continue 349 350 stcp_source, stcp_dest, stcp_seq, stcp_ack_seq, stcp_offset_res, stcp_flags, stcp_window, stcp_check, stcp_urg_ptr = unpack('!HHLLBBHHH',header)351 if evaluateflag(stcp_flags) != "ACK" or stcp_seq!=0:352 print "packet received is not syn ack , resending syn ", stcp_flags353 else:354 355 print "syn ack received"356 winsize = stcp_window357 break358tcp_seq = 1359tcp_ack = 1360tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5)361SYNACKpacket = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr)362sock.sendto(SYNACKpacket, (UDP_IP, UDP_PORT))363print "ack packet sent " , tcp_flags 364print "Can now start receiving data"365logfile = sys.argv[5]366log = open(logfile,'w+')367threads = [] 368try:369 newthread = sendthread()370 newthread.daemon = True371 newthread2 = receivethread()372 newthread2.daemon = True373 newthread.start()374 newthread2.start()375 threads.append(newthread)376 threads.append(newthread2)377 378 for t in threads:379 t.join(600)380 381 382 383except KeyboardInterrupt:384 sys.exit()385 386 ...
IP_TCP.py
Source:IP_TCP.py
1from helper import *2def extract_ip_header(data):3 """4 Use data to generate an IPHeader object5 :param data: the raw data we get, contains IP header, TCP header and data6 :return: an IPHeader object7 """8 ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr = unpack(9 '!BBHHHBBH4s4s', data[0:20])10 source_ip = socket.inet_ntoa(ip_saddr)11 destination_ip = socket.inet_ntoa(ip_daddr)12 ip_ver = ip_ihl_ver >> 413 ip_ihl = ip_ihl_ver & (1 << 5 - 1)14 result = IPHeader(ip_id, source_ip, destination_ip, data[20:], ip_ihl, ip_ver, ip_tos, ip_tot_len, ip_frag_off,15 ip_ttl, ip_proto)16 # Update the IP checksum17 result.ip_check = ip_check18 return result19class IPHeader:20 """21 This class contains all attributes an IP header needs, the payload is a packet with TCP header and data.22 """23 def __init__(self, ip_id, source_ip, destination_ip, payload, ip_ihl=5, ip_ver=4, ip_tos=0, ip_tot_len=0,24 ip_frag_off=0, ip_ttl=255, ip_proto=socket.IPPROTO_TCP):25 self.ip_ihl = ip_ihl26 self.ip_ver = ip_ver27 self.ip_tos = ip_tos28 self.ip_tot_len = ip_tot_len29 self.ip_id = ip_id30 self.ip_frag_off = ip_frag_off31 self.ip_ttl = ip_ttl32 self.ip_proto = ip_proto33 self.ip_check = 034 self.source_ip = source_ip35 self.destination_ip = destination_ip36 self.ip_saddr = socket.inet_aton(source_ip)37 self.ip_daddr = socket.inet_aton(destination_ip)38 self.payload = payload39 def create_ip_header(self):40 """41 Add IP header42 :return: a packet with IP header, TCP header and data43 """44 ip_ihl_ver = (self.ip_ver << 4) + self.ip_ihl45 ip_header = pack('!BBHHHBBH4s4s', ip_ihl_ver, self.ip_tos, self.ip_tot_len, self.ip_id, self.ip_frag_off,46 self.ip_ttl, self.ip_proto, self.ip_check, self.ip_saddr, self.ip_daddr)47 self.ip_check = check_sum(ip_header)48 ip_header = pack('!BBHHHBB', ip_ihl_ver, self.ip_tos, self.ip_tot_len, self.ip_id, self.ip_frag_off,49 self.ip_ttl, self.ip_proto) + pack('H', self.ip_check) + pack('!4s4s', self.ip_saddr,50 self.ip_daddr)51 return ip_header + self.payload52def extract_tcp_header(data):53 """54 Use the data which has removed IP header to generate a TCPHeader object55 :param data:56 :return:57 """58 tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr \59 = unpack('!HHLLBBHHH', data[:20])60 tcp_doff = tcp_offset_res >> 461 adwnd = socket.ntohs(tcp_window)62 payload = data[20:]63 result = TCPHeader(tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_flags, tcp_doff, adwnd, tcp_urg_ptr,64 payload, tcp_check)65 return result66class TCPHeader:67 """68 This class contains all attribute a TCP header needs. Payload is the data.69 """70 def __init__(self, tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, flag, tcp_doff=5, adwnd=64240, tcp_urg_ptr=0,71 payload=b'', tcp_check=0):72 self.tcp_source = tcp_source73 self.tcp_dest = tcp_dest74 self.tcp_seq = tcp_seq75 self.tcp_ack_seq = tcp_ack_seq76 self.tcp_doff = tcp_doff77 self.tcp_window = socket.htons(adwnd)78 self.tcp_check = tcp_check79 self.tcp_urg_ptr = tcp_urg_ptr80 self.tcp_flags = flag81 self.payload = payload82 def create_tcp_header(self, source_ip, destination_ip):83 """84 Add TCP header85 :param source_ip: the source ip address86 :param destination_ip: the destination ip address87 :return: a packet with TCP header and data88 """89 tcp_offset_res = (self.tcp_doff << 4) + 090 tcp_check = 091 user_data = self.payload92 tcp_header = pack('!HHLLBBHHH', self.tcp_source, self.tcp_dest, self.tcp_seq, self.tcp_ack_seq, tcp_offset_res,93 self.tcp_flags, self.tcp_window, tcp_check, self.tcp_urg_ptr)94 tcp_length = len(tcp_header) + len(user_data)95 psh = create_psh(source_ip, destination_ip, socket.IPPROTO_TCP, tcp_length)96 psh = psh + tcp_header + user_data97 tcp_check = check_sum(psh)98 tcp_header = pack('!HHLLBBH', self.tcp_source, self.tcp_dest, self.tcp_seq, self.tcp_ack_seq, tcp_offset_res,99 self.tcp_flags, self.tcp_window) + pack('H', tcp_check) + pack('!H', self.tcp_urg_ptr)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!