def execute(self): logger.debug("Attempting to get kube-dns pod ip") self_ip = sr1(IP(dst="1.1.1.1", ttl=1) / ICMP(), verbose=0, timeout=config.netork_timeout)[IP].dst cbr0_ip, cbr0_mac = self.get_cbr0_ip_mac() kubedns = self.get_kube_dns_ip_mac() if kubedns: kubedns_ip, kubedns_mac = kubedns logger.debug( f"ip={self_ip} kubednsip={kubedns_ip} cbr0ip={cbr0_ip}") if kubedns_mac != cbr0_mac: # if self pod in the same subnet as kube-dns pod self.publish_event( PossibleDnsSpoofing(kubedns_pod_ip=kubedns_ip)) else: logger.debug("Could not get kubedns identity")
def start_discovery(network): for host in network: try: print(f"pinging..... {host}") ack = IP(dst=host) / ICMP() res = sr1(ack, timeout=1, verbose=0) message = f"HOST: {host} || " if not res: message += "UNRESPONSIVE" elif isBlocked(res): message += "BLOCKED" else: message += "OPEN" print(message) message += ',\n' logs.append(message) except Exception as error: print("[ERROR]" + str(error))
def detect_inactive_hosts(scan_hosts): """ Scan the network to find scan_hosts are live or dead scan_hosts can be like 10.0.2.2-4 to cover range. See Scapy docs for specifying targets. """ global scheduler scheduler.enter(RUN_FREQUENCY, 1, detect_inactive_hosts, (scan_hosts, )) inactive_hosts = [] try: ans, unans = sr(IP(dst=scan_hosts)/ICMP(), retry=0, timeout=1) ans.summary(lambda (s,r) : r.sprintf("%IP.src% is alive")) for inactive in unans: print("%s is inactive" % inactive.dst) inactive_hosts.append(inactive.dst) print("Total %d hosts are inactive" % (len(inactive_hosts))) except KeyboardInterrupt: exit(0)
def trace_route(domain_name): """ Main function. Takes the domain name and finds all the ip addresses (hops) on the way to the finale destination, the domain name, using the traceroute logic (TTL). Returns a geojson FeatureCollection with Point and LineString geometry features for drawing on the map. If trace unsuccessful, it returns False. """ feature_list = [] geo_coords_list = [] for i in range(1, 64): try: pkt = IP(dst=domain_name, ttl=i) / ICMP() except: return False resp = sr1(pkt, verbose=0, timeout=1) if resp is None: return False ip_data = get_ip_data(resp.src) # Filter out bogon IP addresses if not ip_data: continue lat, lng = get_lat_lng(ip_data) ip_data_geojson = to_geojson_point(ip_data, lat, lng) # Mapbox requires lng, lat order geo_coords_list.append([lng, lat]) feature_list.append(ip_data_geojson) # Checking for the ICMP echo-reply. Destination reached. if resp.type == 0: # Create LineString feature when all lng and lat values are collected and stored in a list line_string_feature = to_geojson_line_string(geo_coords_list) feature_list.append(line_string_feature) return geojson.FeatureCollection(feature_list)
def GetOsType(self): finalresult = '' try: print("通过Ping判断操作系统类型".center(100, '*')) host = self.domain result = sr1(IP(dst=str(host)) / ICMP(), timeout=1, verbose=0) if result == None: print("无返回结果!\n") finalresult = "无返回结果!\n" elif int(result[IP].ttl) <= 64: print("%s is Linux/Unix\n" % host) finalresult = "%s is Linux/Unix\n" % host else: print("%s is Windows\n" % host) finalresult = "%s is Windows\n" % host except Exception as e: print(e) return finalresult
def send(src, iface, dst, times=15, send_pkt=[]): #filename='/home/shlled/mininet-wifi/Log/UE%s.json' % src[7:8] filename = '/home/shlled/mininet-project-duan/TimeSchedule/Log/DU%s.json' % src[7:8] f=open(filename,'r') buffer=f.readlines() lenth=len(buffer) time.sleep(1) "send the latest info to BS " alpha=buffer[lenth-1] msg = alpha send_pkt.append(msg) p = Ether() / IP(src=src, dst=dst) / ICMP() / msg "wait random seconds, then send in case of collision" t = random.randint(1,10) t = float(t) / 10.0 time.sleep(t) sendp(p, iface = iface) f.close()
def cmd_ping(ip, count, timeout, wait, verbose): conf.verb = False layer3 = IP() layer3.dst = ip layer3.tos = 0 layer3.id = 1 layer3.flags = 0 layer3.frag = 0 layer3.ttl = 64 layer3.proto = 1 # icmp layer4 = ICMP() layer4.type = 8 # echo-request layer4.code = 0 layer4.id = 0 layer4.seq = 0 pkt = layer3 / layer4 counter = 0 while True: ans = sr1(pkt, timeout=timeout) if ans: if verbose: ans.show() else: print(ans.summary()) del (ans) else: print('Timeout') counter += 1 if count != 0 and counter == count: break sleep(wait) return True
def generator(self): n_generations = int(sys.argv[2]) n_packets = int(sys.argv[3]) ip_dst = sys.argv[5] selected_layer = sys.argv[4] # Select the final layer for randomize if selected_layer == "UDP": layer = UDP() elif selected_layer == "TCP": layer = TCP() else: layer = ICMP() for i in range(n_generations): print('Generating packets. (%s of %s)\n' % (i+1, n_generations)) pkts_send = [fuzz(IP(dst=ip_dst, src=RandIP()))/fuzz(layer)/str(RandString()) for j in range(n_packets)] self.send_pkts(pkts_send)
def icmp_craft(pkt, fp, mac): try: ether = Ether() ether.src = mac ether.dst = pkt[Ether].dst ether.type = 0x800 except IndexError: ether = None ip = IP() ip.src = pkt[IP].dst ip.dst = pkt[IP].src ip.ttl = int(fp.probe['IE']['TTL'], 16) dfi_flag = fp.probe['IE']['DFI'] if dfi_flag == 'N': ip.flags = 0 elif dfi_flag == 'S': ip.flags = pkt[IP].flags elif dfi_flag == 'Y': ip.flags = 2 else: ip.flags = 0 if pkt[IP].flags == 2 else 2 ip.id = fp.ip_id_icmp_gen() icmp = ICMP() icmp.type = 0 icmp.id = pkt[ICMP].id cd_val = fp.probe['IE']['CD'] if cd_val == 'Z': icmp.code = 0 elif cd_val == 'S': icmp.code = pkt[ICMP].code else: icmp.code = random.randint(0, 15) icmp.seq = pkt[ICMP].seq data = pkt[ICMP].payload fin_pkt = ip / icmp / data if ether is None else ether / ip / icmp / data return fin_pkt
def fake_sr_return(): """Fake sr response.""" # fake unans pkt_fail = IP(dst="127.0.0.1") / UDP(dport=80, sport=65000) # fake ans pkt_ok_sent = IP(dst="127.0.0.1") / UDP(dport=80, sport=65001) pkt_ok_response = ( IP(dst="127.0.0.1") / ICMP(type="dest-unreach", code="port-unreachable") / IPerror(dst="127.0.0.1") / UDPerror(dport=80, sport=65001) ) pkt_ok_sent.sent_time = 0 pkt_ok_response.time = 0.1 fake_ans = [[pkt_ok_sent, pkt_ok_response]] return (fake_ans, pkt_fail)
def test_00_icmp_accepted(self): for dst in [self.PROXY_HOST, self.ALT_HOST]: pkt = \ IP(dst=dst) / \ UDP(sport=12345, dport=19523) / \ GLBGUE(private_data=GLBGUEChainedRouting(hops=[self.ALT_HOST])) / \ IP(src=self.SELF_HOST, dst=dst) / \ ICMP(type=8, code=0) # echo request # expect a ICMP echo response back from self.PROXY_HOST (decapsulated) resp_ip = self._sendrecv4(pkt, filter='host {} and icmp'.format(dst)) print repr(resp_ip) assert isinstance(resp_ip, IP) assert_equals(resp_ip.src, dst) assert_equals(resp_ip.dst, self.SELF_HOST) resp_icmp = resp_ip.payload assert isinstance(resp_icmp, ICMP) assert_equals(resp_icmp.type, 0) # echo reply assert_equals(resp_icmp.code, 0)
def _ping_device(self, device): """ Ping given device with multiple different methods on network layer. If device is responding return True, otherwise False. Ping is done with following steps: 1. Ping with ARP packet 2. Ping ICMP echo packet 3. Ping with TCP packets to ports 5353 and 62078. (Used in iPhone for Bonjour service and wifi-sync) Core arguments: device -- Device ip address as string, for example '192.168.1.101' Returns: boolean --- If device is responding """ if not device: return False ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=device), retry=5, timeout=2, verbose=False) if ans: log.debug(f"Host {device} is up, responding to ARP") return True ans = sr1(IP(dst=device) / ICMP(), retry=5, timeout=2, verbose=False) if ans: log.debug(f"Host {device} is up, responding to ICMP Echo") return True ans = sr1(IP(dst=device) / TCP(dport=[5353, 62078]), retry=5, timeout=1, verbose=False) if ans: log.debug(f"Host {device} is up, responding to ICP port 62078") return bool(ans)
def traceroute_sr1_to_ans_i(dst_ip,ttl_seq,timeout): """ Esta funcion recibe una ip destino, un ttl, y un timeout y realiza un echo-request; devuelve un diccionario r con los pormenores del resultado. r['ans'] = answered requests r['unans'] = unanswered requests r['time'] = tiempo desde request hasta recibir el reply r['host'] = host que respondio el reply r['hosname'] = hostname (DNS-inverso) que respondio el reply """ from scapy.all import sr, sr1, ICMP, TCP, IP, RandShort import datetime r = {} #r['sr1'] = sr1(IP(dst=dst_ip, ttl=ttl_seq, id=RandShort()) / TCP(flags=0x2), timeout=2, retry=0, verbose=VERBOSE) global ID_GLOBAL ID_GLOBAL += 1 packet = IP(dst=dst_ip, ttl=ttl_seq, id=ID_GLOBAL) / ICMP(type="echo-request") start = datetime.datetime.now() r['ans'],r['unans'] = sr(packet, timeout=0.5, retry=0, verbose=VERBOSE) end = datetime.datetime.now() # python time #r['start_time'] = start #r['end_time'] = end #r['delta_time'] = end-start #r['time'] = "%s ms"%int(round( r['delta_time'].total_seconds() * 1000 )) if r['ans'] != None and len(r['ans']) >= 1 and len(r['ans'][0]) >= 2: r['host'] = r['ans'][0][1][IP].src r['hostname'] = reverse_dns_resolve(r['host']) # packet time r['p_start_time'] = r['ans'][0][0].time r['p_end_time'] = r['ans'][0][1].time r['p_delta_time'] = r['p_end_time']-r['p_start_time'] r['time'] = "%s ms"%int(round( r['p_delta_time'] * 1000 )) else: r['host'] = "*" r['hostname'] = "*" r['time'] = "*" return r
def main(args): print "[*] Comenzando el fuzzing..." pkt_lst = [] for i in xrange(args.count): ip_layer = IP(dst=args.target) # Fuzz IP layer # # Src ramdon? if random_bool(): ip_layer.src = str(RandIP()) # IP ID if random_bool(): ip_layer.id = int(RandShort()) # IP TTL if random_bool(): ip_layer.ttl = int(RandInt()) % 255 icmp_layer = ICMP() # Fuzz ICMP layer # # Type random if random_bool(): icmp_layer.type = int(RandByte()) # Seq random if random_bool(): icmp_layer.seq = int(RandShort()) pkt = ip_layer/icmp_layer pkt_lst.append(pkt) sendp(pkt_lst, inter=args.interval) print "[*] Enviado %s paquetes" % i
def detect_inactive_hosts(scan_hosts): """Scan the network to find scan_hosts are live or dead scan_hosts can be like 10.0.2.2-4 to cover range See scapy docs for specifying target""" global scheduler # schedule.enter(delay, priority, action, (argument1, )) # dealy 延迟时间 # priority 优先级(用于同时间到达的两个事件同时执行时定序) # action 回调函数(被调用触发的函数) # argument1 回调函数参数 # scheduler.enter(RUN_FREQUENCY, 1, detect_inactive_hosts, (scan_hosts, )) inactive_hosts = [] try: # sr 返回有回应的数据包和没有回应的数据包 ans, unans = sr(IP(dst=scan_hosts) / ICMP(), retry=0, timeout=1) ans.summary(lambda (s, r): r.sprintf("%IP.src% is alive")) for inactive in unans: print "%s is inactive" % inactive.dst inactive_hosts.append(inactive.dst) print "Total %d hosts are inactive" % (len(inactive_hosts)) except KeyboardInterrupt: exit(0)
def propagate_token(tokenId): global token_sent # before we send the token we need to check which machines are still alive initialise_listAliveInstance() global listAliveInstances #init snap_shot global current_snapshot current_snapshot = str( listIp[instanceNr - 1]) + ' : ' + str(global_cont) + '\n' for i in range(len(listIpsToForwardToken)): echo_ping = IP(dst=listIpsToForwardToken[i]) / ICMP() / Raw( load=str('echo request')) echo_reply = sr1(echo_ping, verbose=False, timeout=1) if (echo_reply != None): listAliveInstances[i] = True send_message(listIpsToForwardToken[i], 'send token', tokenId) token_sent = True
def main(self, *args): """ Main function """ if not self.ip: try: self.ip = gethostbyname(self.host) except: self._write_result('Host not found: %s' % self.host) return id = randint(0, self.MAX_ID - self.NUMBER_OF_PACKETS) ids = [] # sending packets for i in xrange(self.NUMBER_OF_PACKETS): self._check_stop() packet = IP(dst=self.ip, src=SANDBOX_IP) / ICMP() packet.id = id try: data = sr1(packet, timeout=self.ICMP_TIMEOUT) if not data: raise Exception('Host unreachable') ids.append((i + 1, str(id), str(data.id))) except Exception as e: ids.append((i + 1, str(id), 'N/A (%s)' % str(e))) id += 1 self._write_result('#\tSrc ID\tDst ID') for id in ids: self._write_result('%i\t%s\t%s' % id)
def packet_received(self, packet, **kwargs): """ Call the right handler but also add the source and destination IP as kwargs otherwise after decapsulation it will be lost and upper layers need to get it """ target = self.upperLayers.get(packet.payload.name, self.upperLayers["default"]) kwargs["IP"] = packet.fields id = (packet.src, packet.dst, packet.id) if self.packet_pool.has_key(id): if packet.flags == 1: #MF self.packet_pool[id]["chunk"].append(packet) self.packet_pool[id]["timestamp"] = time.time() else: self.packet_pool[id]["chunk"].append(packet) #Append the packet in order to reassemble them bytes_reassembled = self.reassembly_method(self.packet_pool[id]["chunk"]) self.packet_pool.pop(id) #newpacket = globals()[self.protocols[packet.proto]](bytes_reassembled) proto = self.protocols[packet.proto] if proto == "TCP": newpacket = TCP(bytes_reassembled) elif proto == "ICMP": newpacket = ICMP(bytes_reassembled) elif proto == "UDP": newpacket = UDP(bytes_reassembled) else: raise Exception("Protocol unkown after reassembly") target = self.upperLayers.get(proto, self.upperLayers["default"]) target.packet_received(newpacket, **kwargs) else: if packet.flags == 1: self.packet_pool[(packet.src, packet.dst, packet.id)] = {'timestamp': time.time(), "chunk" : [packet]} else: target.packet_received(packet.payload, **kwargs) now = time.time() for id in self.packet_pool.keys(): if self.packet_pool[id]['timestamp']+30 < now: #Timeout IPv4 fragment reassembly (30 or 60 seconds) (p.448) self.packet_pool.pop(id)
def pkt(self): args = copy.copy(self.cfg) proto = args.pop("proto") if is_proto(proto, "arp"): return ARP(**args) dst = args.pop("dst", None) src = args.pop("src", None) ipver = get_ipver(dst) if ipver == 4: ip = IP(dst=dst, src=src) else: ip = IPv6(dst=dst, src=src) if is_proto(proto, "tcp"): return ip / TCP(**args) elif is_proto(proto, "udp"): return ip / UDP(**args) elif is_proto(proto, "icmp"): return ip / ICMP(**args) elif is_proto(proto, "ospf"): msg = proto[1] if msg == "hello": if ipver == 4: return ip / OSPF_Hdr() / OSPF_Hello(**args) else: return ip / OSPFv3_Hdr() / OSPFv3_Hello(**args) elif msg == "dbdesc": if ipver == 4: return ip / OSPF_Hdr() / OSPF_DBDesc(**args) else: return ip / OSPFv3_Hdr() / OSPFv3_DBDesc(**args)
def test_04_icmp_packet_too_big(self): # Establish full connection, since ICMP is handled differently for # sockets which haven't completed the full 3-way handshake (aka TCP_NEW_SYN_RECV). (eph_port, seq, ack) = self._establish_conn(dport=80) # send a Packet Too Big message via PROXY from ROUTER, which # should end up on the alt host # note that we end on SELF_HOST so it doesn't 'default accept' it pkt = \ IP(dst=self.PROXY_HOST) / \ UDP(sport=12345, dport=19523) / \ GLBGUE(private_data=GLBGUEChainedRouting(hops=[self.ALT_HOST, self.SELF_HOST])) / \ IP(src=self.ROUTER, dst=self.VIP) / \ ICMP(type=3, code=4, nexthopmtu=800) / \ IP(src=self.VIP, dst=self.SELF_HOST) / \ TCP(sport=80, dport=eph_port, seq=ack, ack=seq) alt_host_stream = RemoteSnoop(self.ALT_HOST, remote_iface='tunl0', remote_type=ETH_P_IP) send(pkt) rem_ip = alt_host_stream.recv(lambda pkt: pkt.src == self.ROUTER) # ensure the remote host (ALT_HOST) received the inner packet through the first (failed) hop assert isinstance(rem_ip, IP) assert_equals(rem_ip.src, self.ROUTER) assert_equals(rem_ip.dst, self.VIP) rem_icmp = rem_ip.payload assert isinstance(rem_icmp, ICMP) assert_equals(rem_icmp.type, 3) assert_equals(rem_icmp.code, 4) assert_equals(rem_icmp.nexthopmtu, 800) rem_ipip = rem_icmp.payload assert isinstance(rem_ipip, IP) assert_equals(rem_ipip.src, self.VIP) assert_equals(rem_ipip.dst, self.SELF_HOST) assert_equals(rem_ipip.sport, 80) assert_equals(rem_ipip.dport, eph_port)
def test_02_icmp_fragmentation_required(self): test_packet = Ether() / IP(src="10.11.99.99", dst="1.1.1.1") / ICMP( type=3, code=4) / IP(src="1.1.1.1", dst="10.11.12.13") / TCP( sport=80, dport=45678) self.sendp(test_packet, iface=self.IFACE_NAME_PY) packet = self.wait_for_packet( self.eth_tx, lambda packet: isinstance(packet.payload, IP) and packet.payload.dst == '3.4.5.6') assert isinstance(packet, Ether) assert_equals(packet.dst, self.py_side_mac) fou_ip = packet.payload assert isinstance(fou_ip, IP) # Expecting an IP packet assert_equals(fou_ip.src, '65.65.65.65') assert_equals(fou_ip.dst, '3.4.5.6') fou_udp = fou_ip.payload assert isinstance(fou_udp, UDP) # Expecting a FOU packet assert_equals(fou_udp.sport, self.sport_for_packet(test_packet)) assert_equals(fou_udp.dport, self.DIRECTOR_GUE_PORT) glb_gue = fou_udp.payload assert isinstance( glb_gue, GLBGUE) # Expecting a GUE packet (scapy will always map this) assert_equals(glb_gue.private_data[0].hop_count, 1) assert_equals(glb_gue.private_data[0].next_hop, 0) assert_equals(glb_gue.private_data[0].hops, ['2.3.4.5']) inner_ip = glb_gue.payload assert isinstance(inner_ip, IP) # Expecting the inner IP packet assert_equals(inner_ip.dst, '1.1.1.1') inner_tcp = inner_ip.payload assert isinstance(inner_tcp, ICMP) # Expecting the inner ICMP packet assert_equals(inner_tcp.type, 3) assert_equals(inner_tcp.code, 4)
def ping_sweep(network): # print(type(network)) address_list = [] for ip in network: address_list.append(ip) address_list = address_list[1:-1] # address_list = ["10.0.0.111"] # Testing against a win10 on which I've blocked ICMP traffic for ip in address_list: print("Pinging ",ip,", please wait...") response = sr1( IP(dst=str(ip))/ICMP(), timeout=2, verbose=0 ) print(response) if response == None: print(str(ip) + " is down or unresponsive.") elif response[ICMP].type == 3 and response[ICMP].code == (1 or 2 or 3 or 9 or 10 or 13): # I don't think this is the right syntax, but I'm having trouble finding the right thing print(ip + " is actively blocking ICMP traffic.") else: print(ip + " is reponding")
def start_attack(target_ip): # meaningless bytes in ICMP data field, should be # lower than MTU data = "X" * 500 successful_trials = 0 failed_trials = 0 while True: pkt = IP(dst=target_ip) / ICMP() / data reply = sr1(pkt, timeout=TIMEOUT) if reply is not None: successful_trials += 1 else: failed_trials += 1 success_rate = failed_trials / (successful_trials + failed_trials) with open('attack_stats.txt', 'w+') as the_file: the_file.write("failure rate = {}".format(success_rate))
def __init__(self, target: str, protocol: str = "icmp", max_ttl: int = 30, timeout: int = 5) -> None: self.hops = [] self.max_ttl = max_ttl self.protocol = protocol self.target = target self.time = str(datetime.now()) self.timeout = timeout self.protocol = protocol payloads = { "icmp": ICMP(), "tcp": TCP(dport=53, flags="S"), "udp": UDP() / DNS(qd=DNSQR(qname=self.target)), "http": TCP(dport=80, flags="S"), "tls": TCP(dport=443, flags="S"), } self.payload = payloads.get(self.protocol) self.run() return
def send_query(self, dst, pkt): if self.echo3: echo_pkt = (Ether(dst=self.dns_mac, src=pkt[Ether].dst) / IP(dst=pkt[IP].dst, src=pkt[IP].src) / UDP(dport=pkt[UDP].dport, sport=pkt[UDP].sport) / ICMP(type=3, code=3)) sendp(echo_pkt, iface=self.interface, verbose=0) logging.debug('sending echo error code 3') pkt_rr_type = 1 if ipaddress.ip_address(dst).version == 4 else 28 rpkt = (Ether(dst=pkt[Ether].src, src=pkt[Ether].dst) / IP(dst=pkt[IP].src, src=pkt[IP].dst) / UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport) / DNS(id=pkt[DNS].id, qr=1, ancount=1, qd=pkt[DNS].qd, an=DNSRR(rrname=pkt[DNSQR].qname, rdata=dst, type=pkt_rr_type, ttl=self.ttl))) sendp(rpkt, iface=self.interface, verbose=0) logging.info('spoofed DNS packet sended to %s (redirected to %s)' % (pkt[IP].src, dst))
def check_ip(start, end, networkrange, stop): window.refresh() window["progress"].UpdateBar(0, max=end - start) timeout = 1 window["-output-"].update("") i = 0 for host in range(start, end): if stop(): break ip = networkrange + str(host) try: packet = IP(dst=ip) / ICMP() response = sr1(packet, timeout=timeout, verbose=0) except: break window["progress"].UpdateBar(i + 1) i += 1 if response: if response[ICMP].type == 0: window["-output-"].print(f"{ip} is live") window.refresh() window.write_event_value("-end-task-", "the thread has been end")
def run(val): """ping all hosts in this network""" import urllib from scapy.all import sr, IP, ICMP val = urllib.unquote(val).decode('utf8') print val # ret = [] src = {'method': 'ping', 'type': 'cidr', 'value': val} # #scapy.conf.verb = 0 a, u = sr(IP(dst=val) / ICMP(), timeout=4) for p in a: print p[1].show() dst = { 'method': 'ICMP echo request', 'type': 'ip', 'value': p[1]['IP'].src } ret.append({ 'request': src, 'response': dst }) return ret
def send_packets(self): """Method used to send packets to certain ip address. First, it send ICMP packet to check availability of receiver in network. If he is in network, program sends packets one-by-one and sniff interface for udp packets. """ icmp_packet = IP(self.__ip, ttl=DEFAULT_TTL) / ICMP() reply = sr1(icmp_packet, timeout=DEFAULT_REPLY_TIMEOUT) if reply: for packet_payload in self.__packets: udp_packet = IP(dst=self.__ip) / UDP() / packet_payload sniffer = threading.Thread(target=self.__interface_sniffer, args=(PROTOCOL_TYPE_TO_SNIFF, )) sniffer.start() # required to be able to sniff sent packet sleep(DEFAULT_SLEEP_TIME) send(udp_packet) sniffer.join() else: print(' {0} is offline.'.format(self.__ip))
def get_cbr0_ip_mac(self): config = get_config() res = srp1(Ether() / IP(dst="1.1.1.1", ttl=1) / ICMP(), verbose=0, timeout=config.network_timeout) return res[IP].src, res.src
#! /usr/bin/env python import sys from scapy.all import sr1, IP, ICMP p = sr1(IP(dst=sys.argv[1]) / ICMP()) if p: p.show()