Python socket.SOCK_RAW() Examples

The following are code examples for showing how to use socket.SOCK_RAW(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: aridi   Author: dpgon   File: scan.py    GNU General Public License v3.0 8 votes vote down vote up
def _arppacket(destip, sourceip, sourcemac, iface):
    sourcemac = unhexlify(sourcemac.replace(':', ''))
    broadmac = b'\xFF\xFF\xFF\xFF\xFF\xFF'

    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
    s.bind((iface, socket.htons(3)))

    # Ethernet Header
    protocol = 0x0806   # 0x0806 for ARP
    eth_hdr = pack("!6s6sH", broadmac, sourcemac, protocol)

    # ARP header
    htype = 0x0001      # Hardware type ethernet
    ptype = 0x0800      # Protocol type TCP
    hlen = 0x06         # Hardware address Len
    plen = 0x04         # Protocol addr. len
    operation = 0x0001  # 1=request/2=reply
    src_ip = socket.inet_aton(sourceip)
    dst_ip = socket.inet_aton(destip)
    arp_hdr = pack("!HHBBH6s4s6s4s", htype, ptype, hlen, plen,
                   operation, sourcemac, src_ip, broadmac, dst_ip)

    packet = eth_hdr + arp_hdr

    s.send(packet) 
Example 2
Project: python-decora   Author: mjg59   File: BluetoothSocket.py    MIT License 7 votes vote down vote up
def hci_devinfo(adapter=0):
    # Get Bluetooth device information
    # Takes an adapter number, returns raw data from ioctl
    # FIXME(MR) this function is a complete hack
    # but Python doesn't even dream of offering Bluetooth ioctl's
    dd = BluetoothSocket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)
    dev_info = struct.pack('<H', adapter) + "\x00" * 90
    try:
        r = fcntl.ioctl(dd, 0x800448d3, dev_info) # HCIGETDEVINFO, tested on x64 Linux only
        return r
    except IOError, e:
        # XXX is there a more Pythonic way of doing this?
        if e[0] == 19:
            raise TypeError("No such Bluetooth adapter")
        else:
            raise e 
Example 3
Project: pyuavcan   Author: UAVCAN   File: _socketcan.py    MIT License 7 votes vote down vote up
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 4
Project: deb-ryu   Author: openstack   File: monitor_linux.py    Apache License 2.0 7 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(VRRPInterfaceMonitorNetworkDevice, self).__init__(*args,
                                                                **kwargs)
        self.__is_active = True
        config = self.config
        if config.is_ipv6:
            family = socket.AF_INET6
            ether_type = ether.ETH_TYPE_IPV6
            mac_address = vrrp.vrrp_ipv6_src_mac_address(config.vrid)
        else:
            family = socket.AF_INET
            ether_type = ether.ETH_TYPE_IP
            mac_address = vrrp.vrrp_ipv4_src_mac_address(config.vrid)
        # socket module doesn't define IPPROTO_VRRP
        self.ip_socket = socket.socket(family, socket.SOCK_RAW,
                                       inet.IPPROTO_VRRP)

        self.packet_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
                                           socket.htons(ether_type))
        self.packet_socket.bind((self.interface.device_name, ether_type,
                                 socket.PACKET_MULTICAST,
                                 arp.ARP_HW_TYPE_ETHERNET,
                                 addrconv.mac.text_to_bin(mac_address)))

        self.ifindex = if_nametoindex(self.interface.device_name) 
Example 5
Project: ARPExfiltrator   Author: nocommentlab   File: sender.py    GNU General Public License v3.0 7 votes vote down vote up
def main(payload_to_send):
    """
    Obfuscates the payload, creates the raw Socket and composes the Ethernet Header
    :param: payload_to_send: Buffer of char that contains the payload to send
    """
    obfuscated_payload = Cloakify(payload_to_send, './libs/ipAddresses')

    # Creates the RAW Socket
    rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(__SOCKET_PROTO_TYPE__))
    rawSocket.bind((__SOCKET_BIND_INTERFACE__, socket.htons(__SOCKET_PROTO_TYPE__)))


    # Ethernet Header
    # Format Struct Pack in details:
    # !  = Network, you can use also > to rappresent the bytes order in big-endian
    # 6s = 6 byte of char 
    # 6s = 6 byte of char
    # H  = 2 byte of unsigned short
    eth_hdr = struct.pack("!6s6sH", 
                            binascii.unhexlify(__ARP_HW_DST_ADDRESS__.replace(':', '')), 
                            binascii.unhexlify(__ARP_HW_SOURCE_ADDRESS__.replace(':', '')), 
                            __ETH_PROTO_TYPE__)


    send_arp_requests(rawSocket, eth_hdr, obfuscated_payload) 
Example 6
Project: netmet   Author: godaddy   File: ping.py    Apache License 2.0 6 votes vote down vote up
def _create_socket(self):
        try:
            socket.inet_pton(socket.AF_INET, self.dest)
            dest_ip = self.dest
        except socket.error:
            try:
                dest_ip = socket.gethostbyname(self.dest)
            except socket.gaierror:
                self.ret_code = EXIT_STATUS.ERROR_HOST_NOT_FOUND
                return
        self.dest_ip = dest_ip

        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                      socket.getprotobyname("icmp"))
        except socket.error as e:
            if e.errno == 1:
                self.ret_code = EXIT_STATUS.ERROR_ROOT_REQUIRED
            else:
                self.ret_code = EXIT_STATUS.ERROR_CANT_OPEN_SOCKET
            return 
Example 7
Project: icmp-remote-shell   Author: alex-kostirin   File: common.py    MIT License 6 votes vote down vote up
def start_sniffing(host, log_file):
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    s.bind((host, 0))
    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
    print("Sniffer Started.....")
    while True:
        try:
            data = s.recvfrom(65565)
            d1 = data[0]
            if bytearray(d1)[20] != ICMP_ECHO_REQUEST_TYPE:
                continue
            d1 = str(d1)
            data1 = re.search('@@(.*)\'', d1)
            data_part = data1.group(0)
            data_part = data_part[:len(data_part) - 1]
            writer(data_part, log_file)
            print("Command output:", reader(log_file))
        except:
            pass 
Example 8
Project: npmdocker   Author: hongfeioo   File: ping.py    Apache License 2.0 6 votes vote down vote up
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, (errno, msg):
        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 
Example 9
Project: Nscan   Author: OffensivePython   File: probe.py    Apache License 2.0 6 votes vote down vote up
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 10
Project: Nscan   Author: OffensivePython   File: probe.py    Apache License 2.0 6 votes vote down vote up
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 11
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 12
Project: iSDX   Author: sdn-ixp   File: arproxy.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # info about non-sdn participants
        # TODO: Create a mapping between actual interface IP addresses
        # and the corresponding MAC addresses for all the non-SDN participants
        # In case of MDS, it is actual mac adresses of these interfaces, in case
        # of the superset scheme it is : 1XXXX-nexthop_id
        # self.nonSDN_nhip_2_nhmac = {}
        try:
            self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ETH_TYPE_ARP))
            self.sock.bind((config.interface, 0))
        except socket.error as msg:
            logger.error("Can't open socket %s", str(config.interface))
            logger.exception('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
            raise 
Example 13
Project: auto-check-in   Author: zeekvfu   File: http_utility.py    GNU General Public License v3.0 5 votes vote down vote up
def test_port_open(logger, ip, port, protocol='tcp', retry=2):
    this_func_name = sys._getframe().f_code.co_name
    retry = retry-1
    socket_type = socket.SOCK_STREAM
    if protocol == 'udp':
        socket_type = socket.SOCK_DGRAM
    elif protocol == 'raw':
        socket_type = socket.SOCK_RAW
    flag = False
    try:
        sock = socket.socket(socket.AF_INET, socket_type)
        sock.settimeout(5)
        sock.connect((ip, port))
        flag = True
    except OverflowError as e:
        logger.error("%s(): OverflowError" % this_func_name)
    except socket.timeout as e:
        logger.error("%s(): socket.timeout" % this_func_name)
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    except TimeoutError as e:
        logger.error("%s(): TimeoutError\terrno: %s\tstrerror: %s" % (this_func_name, e.errno, e.strerror))
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    except ConnectionRefusedError as e:
        logger.error("%s(): ConnectionRefusedError\terrno: %s\tstrerror: %s" % (this_func_name, e.errno, e.strerror))
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    except OSError as e:
        logger.error("%s(): OSError\terrno: %s\tstrerror: %s" % (this_func_name, e.errno, e.strerror))
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    finally:
        sock.close()
    logger.info("%s(): retry: %d\tip: %s\tport: %d\tprotocol: %s\tport open: %r" % (this_func_name, retry+1, ip, port, protocol, flag))
    return flag


# 解析得到 URL 对应的 HTML
# 返回值:成功,[delay, content];失败,[-1, exception instance]
# 说明:之所以要返回异常类型,是因为有时侯外层调用者 caller 需要根据异常类型,做针对性地处理 
Example 14
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def serve(self):
		server_socket = None
		self.serverorclient = 1

		try:
			common.internal_print("Starting module: {0} on {1}".format(self.get_module_name(), self.config.get("Global", "serverbind")))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
			if (self.os_type == common.OS_WINDOWS) or (self.os_type == common.OS_MACOSX):
				common.internal_print("This module can be run in client mode only on this operating system.", -1)

				self.cleanup()
				return

			self.comms_socket = server_socket
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

				self.cleanup()
				return

		self.cleanup()

		return 
Example 15
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
			if self.os_type == common.OS_WINDOWS:
				# this should give back the default route interface IP
				default_host_ip = socket.gethostbyname(socket.gethostname())
				server_socket.bind((default_host_ip, 0))

			self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.communication_initialization()
			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 16
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
			if self.os_type == common.OS_WINDOWS:
				# this should give back the default route interface IP
				default_host_ip = socket.gethostbyname(socket.gethostname())
				server_socket.bind((default_host_ip, 0))

			self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False
			self.communication_initialization()
			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)

		self.cleanup()

		return 
Example 17
Project: whatwaff   Author: SVelizDonoso   File: whatwaff.py    MIT License 5 votes vote down vote up
def traceroute(dest_addr, max_hops=30, timeout=0.2):
    print "[*] Verificando Ruta del Servidor :"
    proto_icmp = socket.getprotobyname('icmp')
    proto_udp = socket.getprotobyname('udp')
    port = 33434

    for ttl in xrange(1, max_hops+1):
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto_icmp)
        rx.settimeout(timeout)
        rx.bind(('', port))
        tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto_udp)
        tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        tx.sendto('', (dest_addr, port))

        try:
            data, curr_addr = rx.recvfrom(512)
            curr_addr = curr_addr[0]
        except socket.error:
            curr_addr = None
        finally:
            rx.close()
            tx.close()

        yield curr_addr

        if curr_addr == dest_addr:
            break 
Example 18
Project: ethergeniee   Author: codepaji2006   File: Linux.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, interface):
		self._sockfd = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.SOCK_RAW)
		self._sockfd.bind((interface, socket.SOCK_RAW))
		return 
Example 19
Project: aridi   Author: dpgon   File: scan.py    GNU General Public License v3.0 5 votes vote down vote up
def _scanans(iface):
    global waiting
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))

    while waiting:
        packet = s.recvfrom(2048)

        ethernet_header = packet[0][0:14]
        ethernet_detailed = unpack("!6s6s2s", ethernet_header)

        arp_header = packet[0][14:42]
        arp_detailed = unpack("2s2s1s1s2s6s4s6s4s", arp_header)

        # only listen to ARP packets
        ethertype = ethernet_detailed[2]
        if ethertype == b'\x08\x06':
            sourcemac = hexlify(arp_detailed[5]).decode('utf-8').upper()
            destmac = hexlify(arp_detailed[7]).decode('utf-8').upper()
            sourceip = ip_address(arp_detailed[6])
            destip = ip_address(arp_detailed[8])

            if sourcemac != "000000000000" and sourcemac != "FFFFFFFFFFFF":
                if sourceip not in ipmac:
                    ipmac[sourceip] = sourcemac

            if destmac != "000000000000" and destmac != "FFFFFFFFFFFF":
                if destip not in ipmac:
                    ipmac[destip] = destmac 
Example 20
Project: piescan   Author: m57   File: piescan.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sniffer_thread(target):

    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    sniffer.bind(("0.0.0.0", 0 ))
    sniffer.settimeout(5)
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    # continually read in packets and parse their information
    while ( 1 ):
	try:
	        raw_buffer = sniffer.recvfrom(65565)[0]
        
	except:
		if (SNIFF_MUTEX == 0):
			sys.exit(1)

	ip_header = raw_buffer[0:20]
	dst_port = struct.unpack(">h", raw_buffer[0x32:0x34])[0]
        iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)

        # Create our IP structure
        version_ihl = iph[0]
        ihl = version_ihl & 0xF
        iph_length = ihl * 4
        src_addr = socket.inet_ntoa(iph[8]);

        # Create our ICMP structure
        buf = raw_buffer[iph_length:iph_length + ctypes.sizeof(ICMP)]
        icmp_header = ICMP(buf)

        # check for the type 3 and code and within our target subnet
        if icmp_header.code == 3 and icmp_header.type == 3 and src_addr == target:
		if dst_port not in ports_ident["closed"]:
			ports_ident["closed"].append(dst_port) 
Example 21
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    GNU General Public License v3.0 5 votes vote down vote up
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.
            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 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
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 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
        self.addCleanup(self.s.close)
        try:
            self.s.bind((self.interface,))
        except OSError:
            self.skipTest('network interface `%s` does not exist' %
                           self.interface) 
Example 24
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
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 25
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testCreateSocket(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            pass 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testTooLongInterfaceName(self):
        # most systems limit IFNAMSIZ to 16, take 1024 to be sure
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            self.assertRaisesRegex(OSError, 'interface name too long',
                                   s.bind, ('x' * 1024,)) 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testLoopback(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            for loopback in (0, 1):
                s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
                             loopback)
                self.assertEqual(loopback,
                    s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK)) 
Example 29
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testFilter(self):
        can_id, can_mask = 0x200, 0x700
        can_filter = struct.pack("=II", can_id, can_mask)
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
            self.assertEqual(can_filter,
                    s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter)) 
Example 30
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testCreateSocket(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            pass 
Example 31
Project: vulscan   Author: vulscanteam   File: packet.py    MIT License 5 votes vote down vote up
def send(ip, tcp, payload="", retry=1, timeout=1):
    if timeout <= 0:
        # Avoid entering an infinite waiting loop
        timeout = 0.1
    response = []
    event = threading.Event()
    sock = socket.socket(socket.AF_INET,
                         socket.SOCK_RAW,
                         socket.IPPROTO_RAW)
    # Extracting identifiers
    # ip
    src = ip.source
    dst = ip.destination
    # port
    srcp = struct.pack("!H", tcp.srcp)
    dstp = struct.pack("!H", tcp.dstp)

    tcp.payload = payload
    packet = ip.pack() + tcp.pack(ip.source, ip.destination) + payload

    for i in range(retry):
        t = threading.Thread(target=recv,
                             args=(event, src, dst, srcp,
                                   dstp, response, timeout)
                             )
        t.start()
        try:
            sock.sendto(packet, (socket.inet_ntoa(dst), 0))
        except Exception as e:
            print e
        event.set()
        t.join()
        if not event.isSet():
            break

    if event.isSet():
        return None
    else:
        return response[0] 
Example 32
Project: bluepy.device   Author: IanHarvey   File: hcisocket_linux.py    MIT License 5 votes vote down vote up
def __init__(self, devId):
        self.devId = devId
        self.delegate = None
        self.sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)
        self.sock.bind( (devId,) )
        filt = struct.pack("@LLLH", # struct hci_filter
                    0x14, # type_mask
                    0xC120, 0x40000000, # event_mask[2]
                    0 ) # opcode
        self.sock.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, filt)
        self.packetQueue = []
        self.poller = select.poll()
        self.poller.register(self.sock)
        self.running = False 
Example 33
Project: pingscan   Author: Cashmaney   File: resources.py    MIT License 5 votes vote down vote up
def _create_socket():
    sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_RAW, proto=socket.IPPROTO_ICMP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCK_BUFSIZ)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SOCK_BUFSIZ)
    sock.setblocking(False)
    return sock 
Example 34
Project: ironpython2   Author: IronLanguages   File: test_socket.py    Apache License 2.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 35
Project: avocado-vt   Author: avocado-framework   File: utils_net.py    GNU General Public License v2.0 5 votes vote down vote up
def dellink(self):
        '''
        Delete the interface. Equivalent to 'ip link delete NAME'.
        '''
        # create socket
        sock = socket.socket(socket.AF_NETLINK,
                             socket.SOCK_RAW,
                             arch.NETLINK_ROUTE)

        # Get the interface index
        interface_index = self.get_index()

        # send data to socket
        sock.send(self.__netlink_pack(msgtype=arch.RTM_DELLINK,
                                      flags=arch.NLM_F_REQUEST | arch.NLM_F_ACK,
                                      seq=1, pid=0,
                                      data=struct.pack('BxHiII',
                                                       arch.AF_PACKET,
                                                       0, interface_index, 0, 0)))

        # receive data from socket
        try:
            while True:
                data_recv = sock.recv(1024)
                for msgtype, flags, mseq, pid, data in \
                        self.__netlink_unpack(data_recv):
                    if msgtype == arch.NLMSG_ERROR:
                        (err_no,) = struct.unpack("i", data[:4])
                        if err_no == 0:
                            return 0
                        else:
                            raise DelLinkError(self.name, os.strerror(-err_no))
                    else:
                        raise DelLinkError(self.name, "unexpected error")
        finally:
            sock.close() 
Example 36
Project: connvitals   Author: Comcast   File: ping.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, host: utils.Host, payload: bytes):
		"""
		Inializes a socket connection to the host on port 22, and returns a Pinger object
		referencing it.
		"""

		self.sock, self.icmpParse, self.mkPkt = None, None, None

		if host.family == socket.AF_INET6:
			self.sock = socket.socket(host.family, socket.SOCK_RAW, proto=socket.IPPROTO_ICMPV6)
			self.icmpParse = self._icmpv6Parse
			self.mkPkt = self._mkPkt6
		else:
			self.sock = socket.socket(host.family, socket.SOCK_RAW, proto=socket.IPPROTO_ICMP)
			self.icmpParse = self._icmpv4Parse
			self.mkPkt = self._mkPkt4

		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

		self.sock.settimeout(1)
		self.payload = payload

		#Build a socket object
		self.host = host

		self.timestamps = {} 
Example 37
Project: connvitals   Author: Comcast   File: traceroute.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, host:utils.Host, ID:int, maxHops:int):
		"""
		Constructs a route tracer, including the sockets used to send/recieve
		route tracer packets.

		Not that - unlike the functional implementation - this takes a direct
		integer instead of a whole `Config` object to determine `maxHops`.
		"""
		self.host = host
		self.ID = ID
		self.maxHops = maxHops

		# A bunch of stuff needs to be tweaked if we're using IPv6
		if host.family is socket.AF_INET6:
			# BTW, this doesn't actually work. The RFCs for IPv6 don't define
			# the behaviour of raw sockets - which are heavily utilized by
			# `connvitals`. One of these days, I'll have to implement it using
			# raw ethernet frames ...

			self.receiver = socket.socket(family=host.family,
			                              type=socket.SOCK_RAW,
			                              proto=socket.IPPROTO_ICMPV6)
			self.setTTL = self.setIPv6TTL
			self.isMyTraceResponse = self.isMyIPv6TraceResponse

		else:
			self.receiver = socket.socket(family=host.family,
			                              type=socket.SOCK_RAW,
			                              proto=socket.IPPROTO_ICMP)

		# We need a sender because a UDP socket can't receive ICMP 'TTL
		# Exceeded In Transit' packets, and having a raw sender introduces
		# a slew of new issues.
		self.sender = socket.socket(family=host.family,
		                            type=socket.SOCK_DGRAM)
		self.receiver.settimeout(0.05) 
Example 38
Project: deb-ryu   Author: openstack   File: sample_router.py    Apache License 2.0 5 votes vote down vote up
def _arp_loop(self):
        try:
            with contextlib.closing(
                socket.socket(
                    socket.AF_PACKET, socket.SOCK_RAW,
                    socket.htons(ether.ETH_TYPE_ARP))) as packet_socket:
                packet_socket.bind((self.interface.device_name,
                                    socket.htons(ether.ETH_TYPE_ARP),
                                    socket.PACKET_BROADCAST,
                                    arp.ARP_HW_TYPE_ETHERNET,
                                    mac_lib.BROADCAST))
                self._arp_loop_socket(packet_socket)
        except greenlet.GreenletExit:
            # suppress thread.kill exception
            pass 
Example 39
Project: neutron-qos   Author: eayunstack   File: htb.py    Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        super(RTNetLink, self).__enter__()
        self._sock = socket.socket(
            socket.AF_NETLINK, socket.SOCK_RAW, socket.NETLINK_ROUTE)
        self._sock.bind((self._pid, 0))
        self._seq = int(time.time())
        self._sfd = os.fdopen(self._sock.fileno(), 'w+b')
        return self 
Example 40
Project: python-hcipy   Author: TheBubbleworks   File: hci.py    MIT License 5 votes vote down vote up
def __init__(self, device_id=0):
        self.device_id = device_id
        self._keep_running = True
        self._socket = None
        self._socket_on_data_user_callback = None
        self._socket_poll_thread = None
        self._socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) 
Example 41
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
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 42
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
        self.addCleanup(self.s.close)
        try:
            self.s.bind((self.interface,))
        except OSError:
            self.skipTest('network interface `%s` does not exist' %
                           self.interface) 
Example 43
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
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 44
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 45
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testCreateSocket(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            pass 
Example 46
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testTooLongInterfaceName(self):
        # most systems limit IFNAMSIZ to 16, take 1024 to be sure
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            self.assertRaisesRegex(OSError, 'interface name too long',
                                   s.bind, ('x' * 1024,)) 
Example 47
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testLoopback(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            for loopback in (0, 1):
                s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
                             loopback)
                self.assertEqual(loopback,
                    s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK)) 
Example 48
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testFilter(self):
        can_id, can_mask = 0x200, 0x700
        can_filter = struct.pack("=II", can_id, can_mask)
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
            self.assertEqual(can_filter,
                    s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8)) 
Example 49
Project: shellshockUAscanner   Author: SecureNetworkManagement   File: shellshockUAScanner.py    GNU General Public License v2.0 5 votes vote down vote up
def listenWorker():
    #Socket setup
    sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    sock.bind(('', 1))
    
    #Start ICMP Listener
    #Use Global Listener Flag
    global listenerFlag
    while listenerFlag is True :
       #receive data
       data = sock.recv(1508)

       #ip header is the first 20 bytes
       ip_header = data[:20]

       #ip source address is 4 bytes and is second last field
       ips = ip_header[-8:-4]

       #convert to dotted decimal format
       source = '%i.%i.%i.%i' % (ord(ips[0]), ord(ips[1]), ord(ips[2]), ord(ips[3]))

       #Write to results list
       global resultsList
       resultsList.append(source)
    
#Worker Function 
Example 50
Project: CyberScan   Author: medbenali   File: supersocket.py    GNU General Public License v3.0 5 votes vote down vote up
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 51
Project: CyberScan   Author: medbenali   File: bluetooth.py    GNU General Public License v3.0 5 votes vote down vote up
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 52
Project: CyberScan   Author: medbenali   File: bluetooth.py    GNU General Public License v3.0 5 votes vote down vote up
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 53
Project: CyberScan   Author: medbenali   File: inet6.py    GNU General Public License v3.0 5 votes vote down vote up
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 54
Project: CyberScan   Author: medbenali   File: linux.py    GNU General Public License v3.0 5 votes vote down vote up
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 55
Project: CyberScan   Author: medbenali   File: linux.py    GNU General Public License v3.0 5 votes vote down vote up
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 56
Project: edgedb   Author: edgedb   File: lib.py    Apache License 2.0 5 votes vote down vote up
def is_socket(fd):
    """Determine if the file descriptor is a socket."""
    file_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)

    try:
        file_socket.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
    except socket.error as ex:
        return ex.args[0] != errno.ENOTSOCK
    else:
        return True 
Example 57
Project: xunfeng   Author: ysrc   File: icmp.py    GNU General Public License v3.0 5 votes vote down vote up
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
Example 58
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
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 59
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
        self.addCleanup(self.s.close)
        try:
            self.s.bind((self.interface,))
        except OSError:
            self.skipTest('network interface `%s` does not exist' %
                           self.interface) 
Example 60
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
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 61
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 62
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testCreateSocket(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            pass 
Example 63
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testTooLongInterfaceName(self):
        # most systems limit IFNAMSIZ to 16, take 1024 to be sure
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            self.assertRaisesRegex(OSError, 'interface name too long',
                                   s.bind, ('x' * 1024,)) 
Example 64
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testLoopback(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            for loopback in (0, 1):
                s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
                             loopback)
                self.assertEqual(loopback,
                    s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK)) 
Example 65
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testFilter(self):
        can_id, can_mask = 0x200, 0x700
        can_filter = struct.pack("=II", can_id, can_mask)
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
            self.assertEqual(can_filter,
                    s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter)) 
Example 66
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testCreateSocket(self):
        with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
            pass 
Example 67
Project: icmp-remote-shell   Author: alex-kostirin   File: server.py    MIT License 5 votes vote down vote up
def main():
    args = parse_args()
    host = args.host
    ping_delay = args.ping_delay
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    s.bind((host, 0))
    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
    #  s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
    print("Server Started......")
    while True:
        # while 1:
        data = s.recvfrom(65565)
        d1 = data[0]
        if bytearray(d1)[20] != ICMP_ECHO_REQUEST_TYPE:
            continue
        d1 = str(d1)
        data1 = re.search('@@(.*)', d1)
        command = data1.group(0)
        cmd = command[2:len(command) - 1]
        d = data[1]
        d1 = str(d)
        ip = d1[2:-5]
        # print ip
        print(cmd)  # Holding the command to execute
        print(ip)  # Holding the destination address to send the ping
        output = execute(cmd)
        for line in output.readlines():
            send_one(ip, ping_delay, line) 
Example 68
Project: icmp-remote-shell   Author: alex-kostirin   File: common.py    MIT License 5 votes vote down vote up
def send_one(dest_addr, delay, payload):
    icmp = socket.getprotobyname("icmp")
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    my_id = os.getpid() & 0xFFFF
    send_one_ping(my_socket, dest_addr, my_id, payload)
    my_socket.close()
    time.sleep(delay) 
Example 69
Project: automatic-repo   Author: WZQ1397   File: panelPing.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def do_one(dest_addr, timeout):
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            msg = msg + (
            " - Note that ICMP messages can only be sent from processes"
            " running as root."
          )
            raise socket.error(msg)
        raise # raise the original error 
Example 70
Project: automatic-repo   Author: WZQ1397   File: public.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def do_one(dest_addr, timeout):
    import socket
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            msg = msg + (
            " - Note that ICMP messages can only be sent from processes"
            " running as root."
          )
            return socket.error(msg)
        return timeout*1000; # raise the original error 
Example 71
Project: oss-ftp   Author: aliyun   File: test_socket.py    MIT License 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 72
Project: useful-scripts   Author: opencoff   File: pingsubnet.py    GNU General Public License v2.0 5 votes vote down vote up
def sockv4():
    """Return an IPv4 socket."""
    # can not create a raw socket if not root or setuid to root
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, \
                                   socket.getprotobyname("icmp"))
    except socket.error, e:
        die("You must be root (%s uses raw sockets)" % os.path.basename(sys.argv[0])) 
Example 73
Project: procslink   Author: vfreex   File: __init__.py    MIT License 5 votes vote down vote up
def new_netlink_socket(cls):
        sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, socket.NETLINK_USERSOCK)
        sock.bind((0, 0))
        LOGGER.debug("new Netlink socket created, fd = %s, addr=%s", sock.fileno(), sock.getsockname())
        return sock 
Example 74
Project: icmp_fast_scan   Author: guilhermej   File: icmp_fast_scan.py    MIT License 5 votes vote down vote up
def ping(addr, timeout=1):
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    except Exception as e:
        print e
    packet_id = int((id(timeout) * random.random()) % 65535)
    packet = create_packet(packet_id)
    my_socket.connect((addr, 80))
    my_socket.sendall(packet)
    my_socket.close() 
Example 75
Project: icmp_fast_scan   Author: guilhermej   File: icmp_fast_scan.py    MIT License 5 votes vote down vote up
def listen(responses):
    global SIGNAL
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    s.bind(('', 1))
    print "Listening"
    while SIGNAL:
        packet = s.recv(1024)[:20][-8:-4]
        responses.append(packet)
    print "Stop Listening"
    s.close() 
Example 76
Project: BME280-LoPy-TTN   Author: LoRaWeather   File: LoraConnection.py    MIT License 5 votes vote down vote up
def _createSocket(self):
        self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.socket.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
        self.socket.setblocking(True) 
Example 77
Project: Nscan   Author: OffensivePython   File: probe.py    Apache License 2.0 5 votes vote down vote up
def send(self, hosts, srcp, gen):
		if 'ppp' in self.ifname:
			family = socket.AF_INET
			proto = socket.IPPROTO_RAW
			eth = ''
		else:
			family = socket.AF_PACKET
			proto = ETH_P_IP
			eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack()
		sock = socket.socket(family, socket.SOCK_RAW, proto)
		transport = self.__Transport(srcp, 0)
		npacket = 0
		self.events['send'].wait()
		target = hosts[0]
		while self.events['send'].isSet():
			try:
				target = hosts[0] + gen.next()
				iph = ip.IP(self.diface, dec2dot(target), self.stype)
			except StopIteration:
				break
			for port_list in self.ports:
				for port in range(port_list[0], port_list[1]):
					if self.events['send'].isSet():
						transport.dstp = port
						packet = eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst)
						sock.sendto(packet, (dec2dot(target), 0)) # self.ifname
						npacket+=1
						if not npacket%self.cooldown[0]:
							time.sleep(self.cooldown[1])
					else:
						break
		logging.info('[SEND] Sent: {} packets'.format(npacket))
		sock.close() 
Example 78
Project: Nscan   Author: OffensivePython   File: get.py    Apache License 2.0 5 votes vote down vote up
def Network():
    '''
        send a dns query and capture response packet
        Output:
            ifname: interface name
            ifaddr: interface ip address
            ifmac: interface mac address
            gateway: router mac address
    '''
    sniff = socket.socket(socket.AF_PACKET,
                        socket.SOCK_RAW,
                        socket.htons(0x800))
    while True:
        try:
            socket.gethostbyname('www.google.com')
            data, sa_ll = sniff.recvfrom(65535)
            if sa_ll[2] == socket.PACKET_HOST and sa_ll[0]!='lo':
                break
        except:
            print 'Check your internet connection'
            sniff.close()
            sys.exit()
    sniff.close()

    ifname = sa_ll[0] # interface name
    if 'ppp' in ifname:
        ifmac = mac2byte('00:00:00:00:00:00')
        gateway = mac2byte('00:00:00:00:00:00')
        IPHI = 0    # for ppp interfaces
    else:
        ifmac = data[:6] # interface mac address
        gateway = data[6:12] # gateway mac address
        IPHI = 14   # for eth interfaces
    ifaddr = socket.inet_ntoa(data[IPHI+16:IPHI+20]) # interface ip address
    return ifname, ifaddr, ifmac, gateway 
Example 79
Project: Nscan   Author: OffensivePython   File: probe.py    Apache License 2.0 5 votes vote down vote up
def send(self, hosts, srcp, gen):
		sock = socket.socket(socket.AF_PACKET,
			socket.SOCK_RAW,
			socket.htons(ETH_P_IP))
		nhosts = hosts[1] - hosts[0]
		eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack()
		tcph = tcp.TCP(srcp, 0)
		npacket = 0
		self.events['send'].wait()
		target = hosts[0]
		while self.events['send'].isSet():
			try:
				target = hosts[0] + gen.next()
				iph = ip.IP(self.diface, dec2dot(target))
			except StopIteration:
				break
			for port_list in self.ports:
				for port in range(port_list[0], port_list[1]):
					if self.events['send'].isSet():
						tcph.dstp = port
						packet = eth + iph.pack() + tcph.pack(iph.src, iph.dst)
						sock.sendto(packet, (self.ifname, 0))
						npacket+=1
						if not npacket%self.cooldown[0]:
							time.sleep(self.cooldown[1])
					else:
						break
		logging.info('[SEND] Sent: {} packets'.format(npacket))
		sock.close() 
Example 80
Project: PyonAir-pycom   Author: pyonair   File: LoRaWAN.py    MIT License 4 votes vote down vote up
def __init__(self, logger):
        """
        Connects to LoRaWAN using OTAA and sets up a ring buffer for storing messages.
        :param logger: status logger
        :type logger: LoggerFactory object
        """

        self.logger = logger
        self.message_limit = int(float(config.get_config("fair_access")) / (float(config.get_config("air_time")) / 1000))
        self.transmission_date = config.get_config("transmission_date")  # last date when lora was transmitting
        today = time.gmtime()
        date = str(today[0]) + str(today[1]) + str(today[2])
        if self.transmission_date == date:  # if device was last transmitting today
            self.message_count = config.get_config("message_count")  # get number of messages sent today
        else:
            self.message_count = 0  # if device was last transmitting a day or more ago, reset message_count for the day
            self.transmission_date = date
            config.save_config({"message_count": self.message_count, "transmission_date": date})

        regions = {"Europe": LoRa.EU868, "Asia": LoRa.AS923, "Australia": LoRa.AU915, "United States": LoRa.US915}
        region = regions[config.get_config("region")]

        self.lora = LoRa(mode=LoRa.LORAWAN, region=region, adr=True)

        # create an OTAA authentication parameters
        app_eui = ubinascii.unhexlify(config.get_config("application_eui"))
        app_key = ubinascii.unhexlify(config.get_config("app_key"))

        # join a network using OTAA (Over the Air Activation)
        self.lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

        # create a LoRa socket
        self.lora_socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # request acknowledgment of data sent
        # self.lora_socket.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True)

        # do not request acknowledgment of data sent
        self.lora_socket.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False)

        # sets timeout for sending data
        self.lora_socket.settimeout(int(config.get_config("lora_timeout")) * 1000)

        # set up callback for receiving downlink messages
        self.lora.callback(trigger=LoRa.RX_PACKET_EVENT, handler=self.lora_recv)

        # initialises circular lora stack to back up data up to about 22.5 days depending on the length of the month
        self.lora_buffer = RingBuffer(self.logger, s.processing_path, s.lora_file_name, 31 * self.message_limit, 100)

        try:  # this fails if the buffer is empty
            self.check_date()  # remove messages that are over a month old
        except Exception as e:
            pass