Python socket.SOCK_RAW Examples
The following are 30
code examples of socket.SOCK_RAW().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example #1
Source File: _socketcan.py From pyuavcan with MIT License | 9 votes |
def _make_socket(iface_name: str, can_fd: bool) -> socket.SocketType: s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) try: s.bind((iface_name,)) s.setsockopt(socket.SOL_SOCKET, _SO_TIMESTAMP, 1) # timestamping if can_fd: s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FD_FRAMES, 1) s.setblocking(False) if 0 != s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR): raise OSError('Could not configure the socket: getsockopt(SOL_SOCKET, SO_ERROR) != 0') except BaseException: with contextlib.suppress(Exception): s.close() raise return s
Example #2
Source File: supersocket.py From scapy with GNU General Public License v2.0 | 7 votes |
def __init__(self, type=ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): # noqa: E501 self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # noqa: E501 self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501 self.iface = iface if iface is not None: self.ins.bind((self.iface, type)) if not six.PY2: try: # Receive Auxiliary Data (VLAN tags) self.ins.setsockopt(SOL_PACKET, PACKET_AUXDATA, 1) self.ins.setsockopt( socket.SOL_SOCKET, SO_TIMESTAMPNS, 1 ) self.auxdata_available = True except OSError: # Note: Auxiliary Data is only supported since # Linux 2.6.21 msg = "Your Linux Kernel does not support Auxiliary Data!" log_runtime.info(msg)
Example #3
Source File: ping.py From g3ar with BSD 2-Clause "Simplified" License | 6 votes |
def do_one(dest_addr, timeout): """ Returns either the delay (in seconds) or none on timeout. """ icmp = socket.getprotobyname("icmp") try: my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) except socket.error as xxx_todo_changeme: (errno, msg) = xxx_todo_changeme.args if errno == 1: # Operation not permitted msg = msg + ( " - Note that ICMP messages can only be sent from processes" " running as root." ) raise socket.error(msg) raise # raise the original error my_ID = os.getpid() & 0xFFFF send_one_ping(my_socket, dest_addr, my_ID) delay = receive_one_ping(my_socket, my_ID, timeout) my_socket.close() return delay
Example #4
Source File: ping3.py From ping3 with MIT License | 6 votes |
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56, interface: str = None) -> float or None: """ Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com" timeout: Time to wait for a response, in seconds. Default is 4s, same as Windows CMD. (default 4) unit: The unit of returned value. "s" for seconds, "ms" for milliseconds. (default "s") src_addr: WINDOWS ONLY. The IP address to ping from. This is for multiple network interfaces. Ex. "192.168.1.20". (default None) interface: LINUX ONLY. The gateway network interface to ping from. Ex. "wlan0". (default None) ttl: The Time-To-Live of the outgoing packet. Default is 64, same as in Linux and macOS. (default 64) seq: ICMP packet sequence, usually increases from 0 in the same process. (default 0) size: The ICMP packet payload size in bytes. If the input of this is less than the bytes of a double format (usually 8), the size of ICMP packet payload is 8 bytes to hold a time. The max should be the router_MTU(Usually 1480) - IP_Header(20) - ICMP_Header(8). Default is 56, same as in macOS. (default 56) Returns: The delay in seconds/milliseconds or None on timeout. Raises: PingError: Any PingError will raise again if `ping3.EXCEPTIONS` is True. """ with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as sock: sock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) if interface: sock.setsockopt(socket.SOL_SOCKET, SOCKET_SO_BINDTODEVICE, interface.encode()) # packets will be sent from specified interface. _debug("Socket Interface Binded:", interface) if src_addr: sock.bind((src_addr, 0)) # only packets send to src_addr are received. _debug("Socket Source Address Binded:", src_addr) thread_id = threading.get_native_id() if hasattr(threading, 'get_native_id') else threading.currentThread().ident # threading.get_native_id() is supported >= python3.8. process_id = os.getpid() # If ping() run under different process, thread_id may be identical. icmp_id = zlib.crc32("{}{}".format(process_id, thread_id).encode()) & 0xffff # to avoid icmp_id collision. try: send_one_ping(sock=sock, dest_addr=dest_addr, icmp_id=icmp_id, seq=seq, size=size) delay = receive_one_ping(sock=sock, icmp_id=icmp_id, seq=seq, timeout=timeout) # in seconds except errors.HostUnknown as e: # Unsolved _debug(e) _raise(e) return False except errors.PingError as e: _debug(e) _raise(e) return None if delay is None: return None if unit == "ms": delay *= 1000 # in milliseconds return delay
Example #5
Source File: probe.py From Nscan with Apache License 2.0 | 6 votes |
def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter = 0 while self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1 if counter==self.count: self.events['send'].clear() break except socket.timeout: continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter))
Example #6
Source File: probe.py From Nscan with Apache License 2.0 | 6 votes |
def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) sock.bind((self.diface, 0)) sock.settimeout(5) self.events['recv'].wait() counter = 0 while self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535) self.queue.put(Extract(data)) counter += 1 if counter==self.count: self.events['send'].clear() break except socket.timeout: continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter))
Example #7
Source File: ping.py From g3ar with BSD 2-Clause "Simplified" License | 6 votes |
def do_one(dest_addr, timeout): """ Returns either the delay (in seconds) or none on timeout. """ icmp = socket.getprotobyname("icmp") try: my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) except socket.error as xxx_todo_changeme: (errno, msg) = xxx_todo_changeme.args if errno == 1: # Operation not permitted msg = msg + ( " - Note that ICMP messages can only be sent from processes" " running as root." ) raise socket.error(msg) raise # raise the original error my_ID = os.getpid() & 0xFFFF send_one_ping(my_socket, dest_addr, my_ID) delay = receive_one_ping(my_socket, my_ID, timeout) my_socket.close() return delay
Example #8
Source File: socket_handler.py From traceflow with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, ip_daddr): # We're only interested in ICMP, so happy to have this hard coded. try: self.icmp_listener = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp") ) except PermissionError as e: print(e) print("Please run as root!") exit(1) # TODO: Test Timestamps correctly try: SO_TIMESTAMPNS = 35 self.icmp_listener.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1) except OSError as e: logging.debug("Timestamps not available, continuing without them for now") self.ip_daddr = ip_daddr self.mutex = threading.Lock() logging.debug("Starting") self.icmp_packets = dict() t = threading.Thread(target=self.listener) t.setDaemon(True) t.start()
Example #9
Source File: traceroute.py From FinalRecon with MIT License | 6 votes |
def tcp_trace(ip, port, tr_tout, output, collect): status = {'end': False} rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) rx.setblocking(0) rx.settimeout(tr_tout) rx.bind(('', 0)) print('\n' + R + 'HOPS'.ljust(7) + 'IP'.ljust(17) + 'HOST' + W + '\n') for ttl in range(1,31): t = threading.Thread(target=tcp_send(ip, port, ttl, rx, status, tr_tout, output, collect), daemon=True) t = t.start() if status['end'] == True: break rx.close()
Example #10
Source File: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 6 votes |
def addListener(self, addr, port, service): if self.isBroadcast(addr): self.etherAddrs[addr] = self.broadcastIpToMac(addr) elif self.isMulticast(addr): self.etherAddrs[addr] = self.multicastIpToMac(addr) else: # unicast -- we don't know yet which IP we'll want to send to self.etherAddrs[addr] = None # Set up the receiving socket and corresponding IP and interface information. # One receiving socket is required per multicast address. rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) for interface in self.interfaces: (ifname, mac, ip, netmask) = self.getInterface(interface) # Add this interface to the receiving socket's list. if self.isBroadcast(addr): rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) elif self.isMulticast(addr): packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip)) rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress) # Generate a transmitter socket. Each interface # requires its own transmitting socket. if interface not in self.noTransmitInterfaces: tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) tx.bind((ifname, 0)) self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service}) rx.bind((addr, port)) self.receivers.append(rx)
Example #11
Source File: dnsmasploit.py From raw-packet with MIT License | 6 votes |
def send_dhcpv6_solicit(): Client_DUID = dhcpv6r.get_duid(macsrc) request_options = [23, 24] pkt = dhcpv6r.make_solicit_packet(ethernet_src_mac=macsrc, ipv6_src=ipv6src_link, transaction_id=randint(1, 16777215), client_identifier=Client_DUID, option_request_list=request_options) try: SOCK = socket(AF_PACKET, SOCK_RAW) SOCK.bind((current_network_interface, 0)) SOCK.send(pkt) print(Base.c_info + 'Send Solicit request to: [ff02::1:2]:547') SOCK.close() except: print(Base.c_error + 'Do not send Solicit request.') exit(1)
Example #12
Source File: bluetooth.py From scapy with GNU General Public License v2.0 | 5 votes |
def __init__(self, iface=0x10000, type=None): if WINDOWS: warning("Not available on Windows") return s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) # noqa: E501 s.setsockopt(socket.SOL_HCI, socket.HCI_DATA_DIR, 1) s.setsockopt(socket.SOL_HCI, socket.HCI_TIME_STAMP, 1) s.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, struct.pack("IIIh2x", 0xffffffff, 0xffffffff, 0xffffffff, 0)) # type mask, event mask, event mask, opcode # noqa: E501 s.bind((iface,)) self.ins = self.outs = s # s.connect((peer,0))
Example #13
Source File: bluetooth.py From scapy with GNU General Public License v2.0 | 5 votes |
def __init__(self, bt_address, port=0): s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_RFCOMM) s.connect((bt_address, port)) self.ins = self.outs = s
Example #14
Source File: bluetooth.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def __init__(self, iface=0x10000, type=None): s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) s.setsockopt(socket.SOL_HCI, socket.HCI_DATA_DIR,1) s.setsockopt(socket.SOL_HCI, socket.HCI_TIME_STAMP,1) s.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, struct.pack("IIIh2x", 0xffffffffL,0xffffffffL,0xffffffffL,0)) #type mask, event mask, event mask, opcode s.bind((iface,)) self.ins = self.outs = s # s.connect((peer,0))
Example #15
Source File: dns_proxy.py From dnxfirewall-cmd with GNU General Public License v3.0 | 5 votes |
def listener_sock(self): l_sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.IPPROTO_UDP) l_sock.bind((self._intf, 3)) return l_sock
Example #16
Source File: test_socket.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def _have_socket_can(): """Check whether CAN sockets are supported on this host.""" try: s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) except (AttributeError, OSError): return False else: s.close() return True
Example #17
Source File: bluetooth.py From CVE-2016-6366 with MIT License | 5 votes |
def __init__(self, iface=0x10000, type=None): s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) s.setsockopt(socket.SOL_HCI, socket.HCI_DATA_DIR,1) s.setsockopt(socket.SOL_HCI, socket.HCI_TIME_STAMP,1) s.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, struct.pack("IIIh2x", 0xffffffffL,0xffffffffL,0xffffffffL,0)) #type mask, event mask, event mask, opcode s.bind((iface,)) self.ins = self.outs = s # s.connect((peer,0))
Example #18
Source File: dnx_parent_classes.py From dnxfirewall-cmd with GNU General Public License v3.0 | 5 votes |
def listener_sock(self): '''returns new socket object to be used with interface registration. May be overriden. ''' sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) sock.bind((self._intf, 3)) return sock
Example #19
Source File: bluetooth.py From CVE-2016-6366 with MIT License | 5 votes |
def __init__(self, peer): s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_L2CAP) s.connect((peer,0)) self.ins = self.outs = s
Example #20
Source File: supersocket.py From CVE-2016-6366 with MIT License | 5 votes |
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
Example #21
Source File: test_socket.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def clientSetUp(self): self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) try: self.cli.bind((self.interface,)) except OSError: # skipTest should not be called here, and will be called in the # server instead pass
Example #22
Source File: linux.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None, nofilter=0): self.type = type self.outs = None self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) _flush_fd(self.ins) if iface is not None: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) if promisc is None: promisc = conf.sniff_promisc self.promisc = promisc if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] if self.promisc: for i in self.iff: set_promisc(self.ins, i) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
Example #23
Source File: linux.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0): self.type = type self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) _flush_fd(self.ins) if iface: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30) if promisc is None: promisc = conf.promisc self.promisc = promisc if self.promisc: if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] for i in self.iff: set_promisc(self.ins, i)
Example #24
Source File: inet6.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def __init__(self, type = ETH_P_IPV6, filter=None, iface=None, promisc=None, nofilter=0): L3RawSocket.__init__(self, type, filter, iface, promisc) # NOTE: if fragmentation is needed, it will be done by the kernel (RFC 2292) self.outs = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_RAW) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
Example #25
Source File: linux.py From CVE-2016-6366 with MIT License | 5 votes |
def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None, nofilter=0): self.type = type self.outs = None self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) _flush_fd(self.ins) if iface is not None: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) if promisc is None: promisc = conf.sniff_promisc self.promisc = promisc if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] if self.promisc: for i in self.iff: set_promisc(self.ins, i) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
Example #26
Source File: bluetooth.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def __init__(self, peer): s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_L2CAP) s.connect((peer,0)) self.ins = self.outs = s
Example #27
Source File: supersocket.py From smod-1 with GNU General Public License v2.0 | 5 votes |
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) if iface is not None: self.ins.bind((iface, type))
Example #28
Source File: socket_handler.py From traceflow with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, daddr): try: self.raw_sock = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW ) except PermissionError as e: print(e) print("Please run as root!") exit(1) self.ip_daddr = daddr os_release = platform.system() if os_release == "Darwin": # Boned. TODO: Work on fixing this. print("Detected Mac OS - Cannot support writing of raw IP packets, exiting") exit(1) if os_release.endswith("BSD"): # BSD - Need to explicit set IP_HDRINCL. # BSD - Need to explicitly calculate IP total length self.raw_sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) logging.debug("Detected a BSD") if os_release == "Linux": # Linux - No need to set IP_HDRINCL,as setting SOCK_RAW auto sets this. However should be explicit in settings. self.raw_sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) logging.debug("Detected Linux") if os_release == "Windows": # No idea - No ability to test. Maybe abort? # TODO: Find testers? logging.debug("Detected NT") print("Untested on Windows - Exiting") exit(1)
Example #29
Source File: dhcp_starvation.py From raw-packet with MIT License | 5 votes |
def send_dhcp_discover(): sleep(1) base.print_info("Sending DHCP discover packets...") base.print_info("Delay between DISCOVER packets: ", str(args.delay), " sec.") base.print_info("Start sending packets: ", str(datetime.now().strftime("%Y/%m/%d %H:%M:%S"))) discover_raw_socket = socket(AF_PACKET, SOCK_RAW) discover_raw_socket.bind((listen_network_interface, 0)) try: while True: client_mac = eth.make_random_mac() transaction_id = randint(1, 4294967295) discover_raw_socket.send(dhcp.make_discover_packet(ethernet_src_mac=your_mac_address, client_mac=client_mac, transaction_id=transaction_id, relay_agent_ip=your_ip_address)) transactions[transaction_id] = client_mac if int(time() - start_time) > args.timeout: if ack_received: base.print_success("IP address pool is exhausted: ", str(datetime.now().strftime("%Y/%m/%d %H:%M:%S"))) else: base.print_error("DHCP Starvation failed timeout!") sleep(1) exit(1) sleep(int(args.delay)) except KeyboardInterrupt: base.print_info("Exit") discover_raw_socket.close() exit(0) # endregion # region Send DHCP request
Example #30
Source File: send_tcp_packets.py From raw-packet with MIT License | 5 votes |
def arp_reply(your_mac_address, your_ip_address, target_mac_address, target_ip_address): SOCK = socket(AF_PACKET, SOCK_RAW) SOCK.bind((current_network_interface, 0)) arp_reply = arp.make_response(ethernet_src_mac=your_mac_address, ethernet_dst_mac=target_mac_address, sender_mac=your_mac_address, sender_ip=your_ip_address, target_mac=target_mac_address, target_ip=target_ip_address) SOCK.send(arp_reply) SOCK.close()