Python socket.SOCK_RAW() Examples

The following are code examples for showing how to use socket.SOCK_RAW(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: raw-packet   Author: Vladimir-Ivanov-Git   File: network_conflict_creator.py    (license) View Source Project 8 votes vote down vote up
def send_arp_reply(request):
    if request.haslayer(ARP):
        global _current_number_of_packets
        global _current_network_interface
        global _current_mac_address
        global _arp

        SOCK = socket(AF_PACKET, SOCK_RAW)
        SOCK.bind((_current_network_interface, 0))

        if request[ARP].op == 1:
            if request[Ether].dst == "ff:ff:ff:ff:ff:ff" and request[ARP].hwdst == "00:00:00:00:00:00":
                print Base.c_info + "ARP request from MAC: " + request[ARP].hwsrc + " IP: " + request[ARP].pdst
                reply = _arp.make_response(ethernet_src_mac=_current_mac_address,
                                           ethernet_dst_mac=request[ARP].hwsrc,
                                           sender_mac=_current_mac_address, sender_ip=request[ARP].pdst,
                                           target_mac=request[ARP].hwsrc, target_ip=request[ARP].psrc)
                SOCK.send(reply)
                _current_number_of_packets += 1
                if _current_number_of_packets >= _number_of_packets:
                    SOCK.close()
                    exit(0) 
Example 2
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 3_2_ping_remote_host.py    (license) View Source Project 7 votes vote down vote up
def ping_once(self):
        """
        Returns the delay (in seconds) or none on timeout.
        """
        icmp = socket.getprotobyname("icmp")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error as e:
            if e.errno == 1:
                # Not superuser, so operation not permitted
                e.msg +=  "ICMP messages can only be sent from root user processes"
                raise socket.error(e.msg)
        except Exception as e:
            print ("Exception: %s" %(e))
    
        my_ID = os.getpid() & 0xFFFF
     
        self.send_ping(sock, my_ID)
        delay = self.receive_pong(sock, my_ID, self.timeout)
        sock.close()
        return delay 
Example 3
Project: python-backdoor   Author: HackersArena   File: client.py    (license) View Source Project 7 votes vote down vote up
def sniffer_dog():

    rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    rawSocket.bind(('127.0.0.1',0))

    receivedPacket = rawSocket.recv(2048)

    ipHeader = receivedPacket[0:20]
    ipHdr = struct.unpack("!12s4s4s",ipHeader)
    sourceIP = socket.inet_ntoa(ipHdr[0])
    destinationIP = socket.inet_ntoa(ipHdr[2])

    tcpHeader = receivedPacket[34:54]
    tcpHdr = struct.unpack("!2s2s16s",tcpHeader)
    sourcePort = socket.inet_ntoa(tcpHdr[0])
    destinationPort = socket.inet_ntoa(tcpHdr[1])
    return list(sourceIP, destinationIP, sourcePort, destinationPort)

# To identify your public IP (attacker's public IP) 
Example 4
Project: XFLTReaT   Author: earthquake   File: ICMP.py    (license) View Source Project 7 votes vote down vote up
def serve(self):
		server_socket = None
		try:
			common.internal_print("Starting server: {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)
			whereto = (self.config.get("Global", "serverbind"), self.ICMP_fake_serverport)

			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False

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

				self.cleanup()
				return

		self.cleanup()

		return 
Example 5
Project: code   Author: ActiveState   File: recipe-577523.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, ifname, user_id=None, user_pw=None, interactive=False):

        self.state = 0

        self.user_id = user_id
        self.user_pw = user_pw

        self.interactive = interactive

        self.assoc_hwaddr = None

        self.ifname = ifname
        self.sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_PAE))
        self.sock.bind((ifname, 0))
        self.ifindex = get_ifindex(self.sock, self.ifname)
        self.hwaddr = get_hwaddr(self.sock, self.ifname)

        SOL_PACKET = 263
        PACKET_ADD_MEMBERSHIP = 1
        self.sock.setsockopt(SOL_PACKET, PACKET_ADD_MEMBERSHIP,
                build_mreq(self.ifindex)) 
Example 6
Project: fdslight   Author: fdslight   File: traffic_pass.py    (license) View Source Project 6 votes vote down vote up
def init_func(self, creator_fd):
        self.__creator_fd = creator_fd
        self.__sent = []

        family = socket.AF_INET

        s = socket.socket(family, socket.SOCK_RAW,
                          socket.IPPROTO_UDP | socket.IPPROTO_ICMP | socket.IPPROTO_UDP | 136)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
        s.setblocking(0)

        self.__socket = s
        self.set_fileno(s.fileno())
        self.register(self.fileno)
        self.add_evt_read(self.fileno)

        return self.fileno 
Example 7
Project: Theseus   Author: Dylan-halls   File: ping.py    (license) View Source Project 6 votes vote down vote up
def await_responce(self, iface):
		global rev
		r = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
		pkt = r.recvfrom(2048)
		
		eth = pkt[0][0:14]
		eth_d = struct.unpack("!6s6s2s", eth)
		res = binascii.hexlify(eth_d[0])

		dst_mac = self.format_mac(res.decode('utf-8'))

		local_mac = open('/sys/class/net/{}/address'.format(iface)).read().strip('\n')
 		
		if dst_mac == local_mac:
			stop_time = datetime.datetime.now()
			arp_h = pkt[0][14:42]
			arp_d = struct.unpack("2s2s1s1s2s6s4s6s4s", arp_h)
			timee = stop_time - start_time
			rev += 1
			return self.format_mac(binascii.hexlify(arp_d[5]).decode('utf-8')), arp_d[6], timee.total_seconds() * 1000 
Example 8
Project: taf   Author: taf3   File: dev_pypacker.py    (license) View Source Project 6 votes vote down vote up
def get_os_mtu(self, iface=None):
        """Get MTU value in host OS.

        Args:
            iface(str):  Interface for getting MTU in host OS

        Returns:
            int: Original MTU value

        Examples::

            env.tg[1].get_os_mtu(iface=ports[('tg1', 'sw1')][1])

        """
        try:
            soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
            ifr = struct.pack('16sH', iface.encode("utf-8"), 0)
            mtu = struct.unpack('16sH', ioctl(soc, self.SIOCGIFMTU, ifr))[1]
        except Exception as err:
            raise PypackerException("ERROR: Getting MTU failed; {}".format(err))

        return mtu 
Example 9
Project: taf   Author: taf3   File: dev_pypacker.py    (license) View Source Project 6 votes vote down vote up
def set_os_mtu(self, iface=None, mtu=None):
        """Set MTU value in host OS.

        Args:
            iface(str):  Interface for changing MTU in host OS
            mtu(int):  New MTU value

        Returns:
            int:  Original MTU value

        Examples::

            env.tg[1].set_os_mtu(iface=ports[('tg1', 'sw1')][1], mtu=1650)

        """
        try:
            soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
            ioctl(soc, self.SIOCSIFMTU, struct.pack('16sH', iface.encode("utf-8"), mtu) + b'\x00' * self.ETHER_HEADER)
        except Exception as err:
            raise PypackerException("ERROR: Setting MTU failed: {}".format(err)) 
Example 10
Project: NetPower_TestBed   Author: Vignesh2208   File: basicHostIPCLayer.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, hostID, logFile,sharedBufferArray):
        threading.Thread.__init__(self)

        self.threadCmdLock = threading.Lock()
        self.threadCallbackQueue = {}
        self.threadCallbackLock = threading.Lock()
        self.nPendingCallbacks = 0

        self.threadCmdQueue = []
        self.hostID = hostID
        self.sharedBufferArray = sharedBufferArray
        self.log = logger.Logger(logFile, "Host " + str(hostID) + " IPC Thread")
        self.hostIDtoPowerSimID = None
        self.powerSimIDtohostID = None
        self.attackLayer = None
        self.raw_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.init_shared_ipc_buffer()

    # self.raw_sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 
Example 11
Project: netmet   Author: godaddy   File: ping.py    (license) View Source Project 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 12
Project: isf   Author: w3h   File: icmp_ping.py    (license) View Source Project 6 votes vote down vote up
def ping_once(self):
        """
        Returns the delay (in seconds) or none on timeout.
        """
        icmp = socket.getprotobyname("icmp")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error, (errno, msg):
            if errno == 1:
                # Not superuser, so operation not permitted
                msg +=  "ICMP messages can only be sent from root user processes"
                raise socket.error(msg)
        except Exception, e:
            print "Exception: %s" %(e)
    
        my_ID = os.getpid() & 0xFFFF
     
        self.send_ping(sock, my_ID)
        delay = self.receive_pong(sock, my_ID, self.timeout)
        sock.close()
        return delay 
Example 13
Project: web_ctp   Author: molebot   File: test_socket.py    (license) View Source Project 6 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 14
Project: raw-packet   Author: Vladimir-Ivanov-Git   File: dnsmasploit.py    (license) View Source Project 6 votes vote down vote up
def send_dhcpv6_solicit():
    Client_DUID = dhcpv6r.get_client_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 15
Project: g3ar   Author: VillanCh   File: ping.py    (license) View Source Project 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 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 16
Project: g3ar   Author: VillanCh   File: ping.py    (license) View Source Project 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 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 17
Project: ryu-lagopus-ext   Author: lagopus   File: monitor_linux.py    (license) View Source Project 6 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 18
Project: py-sys   Author: vicky-tan   File: ping_icmp.py    (license) View Source Project 6 votes vote down vote up
def ping_once(self, dest_addr, timeout, sequence):
        icmp = socket.getprotobyname('icmp')
        
        try:
            icmp_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error, (errno, msg):
            if errno == 1:
                msg = '%s : Just root can send ICMP Message' % msg
                raise socket.error(msg)
            raise
     
        packet_id = os.getpid() & 0xFFFF
     
        self.__send_icmp_request(icmp_socket, dest_addr, packet_id, sequence)
        delay = self.__receive_icmp_response(icmp_socket, packet_id, timeout)
     
        icmp_socket.close()
        return delay 
Example 19
Project: Network   Author: Momingcoder   File: icmp-ping.py    (license) View Source Project 6 votes vote down vote up
def ping_once(ip_addr, timeout):
    """
    return either delay (in second) or none on timeout.
    """
    # Translate an Internet protocol name to a constant suitable for
    # passing as the (optional) third argument to the socket() function.
    # This is usually only needed for sockets opened in “raw” mode.
    icmp = socket.getprotobyname('icmp')
    try:
        # socket.socket([family[, type[, proto]]])
        # Create a new socket using the given address family(default: AF_INET),
        # socket type(SOCK_STREAM) and protocol number(zero or may be omitted).
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error:
        raise

    # Return the current process id.
    # int: 0xFFFF = -1, unsigned int: 65535
    my_ID = os.getpid() & 0xFFFF

    send_ping(my_socket, ip_addr, my_ID)
    delay = receive_ping(my_socket, my_ID, timeout)

    my_socket.close()
    return delay 
Example 20
Project: WiPy-LoPy   Author: Enabling   File: connection.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, deviceAddress, applicationKey, networkKey):
        from network import LoRa
        import socket
        import binascii
        import struct
        self.deviceAddress = deviceAddress
        self.applicationKey = applicationKey
        self.networkKey = networkKey
        self.lora = LoRa(mode=LoRa.LORAWAN)
        dev_addr = struct.unpack(">l", binascii.unhexlify(deviceAddress.replace(' ','')))[0]
        nwk_swkey = binascii.unhexlify(networkKey.replace(' ',''))
        app_swkey = binascii.unhexlify(applicationKey.replace(' ',''))
        self.lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))
        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
        self.s.setblocking(False) 
Example 21
Project: nav   Author: UNINETT   File: megaping.py    (license) View Source Project 6 votes vote down vote up
def make_sockets():
    """Makes and returns the raw IPv6 and IPv4 ICMP sockets.

    This needs to run as root before dropping privileges.

    """
    try:
        socketv6 = socket.socket(socket.AF_INET6, socket.SOCK_RAW,
                                 socket.getprotobyname('ipv6-icmp'))
    except Exception:
        LOGGER.error("Could not create v6 socket")
        raise

    try:
        socketv4 = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                 socket.getprotobyname('icmp'))
    except Exception:
        LOGGER.error("Could not create v6 socket")
        raise

    return [socketv6, socketv4] 
Example 22
Project: minihydra   Author: VillanCh   File: ping.py    (license) View Source Project 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 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 23
Project: ICMPTunnel   Author: T3rry7f   File: IcmpTunnel_C.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,MODE):
        self.ICMP_ECHO_REQUEST = 0x08 
        self.ICMP_ECHO_REPLY= 0x00
        if (MODE==0):
            self.ICMP_SEND=self.ICMP_ECHO_REPLY
            self.ICMP_RECV=self.ICMP_ECHO_REQUEST
            self.ICMP_CODE=0x00
        else:
            self.ICMP_RECV=self.ICMP_ECHO_REPLY
            self.ICMP_SEND=self.ICMP_ECHO_REQUEST
            self.ICMP_CODE=0x00
            
        self.MAX_DATA_SIZE=1024
        self.TIMEOUT=300
        self.ID=0x100
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,socket.getprotobyname("icmp")) 
Example 24
Project: ICMPTunnel   Author: T3rry7f   File: IcmpTunnel_S.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,MODE):
        self.ICMP_ECHO_REQUEST = 0x08 
        self.ICMP_ECHO_REPLY= 0x00
        if (MODE==0):
            self.ICMP_SEND=self.ICMP_ECHO_REPLY
            self.ICMP_RECV=self.ICMP_ECHO_REQUEST
            self.ICMP_CODE= 0x00
        else:
            self.ICMP_RECV=self.ICMP_ECHO_REPLY
            self.ICMP_SEND=self.ICMP_ECHO_REQUEST
            self.ICMP_CODE= 0x00

        self.MAX_DATA_SIZE=1024
        self.TIMEOUT=300
        self.ID=0x100
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,socket.getprotobyname("icmp")) 
Example 25
Project: Charlie   Author: nxintech   File: sniffer.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, interface_name, on_ip_incoming, on_ip_outgoing):

        self.interface_name = interface_name
        self.on_ip_incoming = on_ip_incoming
        self.on_ip_outgoing = on_ip_outgoing

        # The raw in (listen) socket is a L2 raw socket that listens
        # for all packets going through a specific interface.
        # SOL_SOCKET: SO_LINGER, SO_RCVBUF, SO_SNDBUF, TCP_NODELAY
        # SO_LINGER ???????????????????TIME_WAIT?????
        # ????????????????????tcp??
        # SO_RCVBUF?SO_SNDBUF ????????????????
        # SO_SNDBUF ?? MSS??????? 2MSS
        # TCP_NODELAY  ?? nagle ??
        self.sock = socket.socket(
            socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_IP))
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 ** 30)
        self.sock.bind((self.interface_name, ETH_P_IP)) 
Example 26
Project: XFLTReaT   Author: earthquake   File: ICMP.py    (license) View Source Project 6 votes vote down vote up
def client(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)
			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_auth()
			self.communication(False)

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

		self.cleanup()

		return 
Example 27
Project: XFLTReaT   Author: earthquake   File: ICMP.py    (license) View Source Project 6 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)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = True
			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 28
Project: kakeup   Author: Ventto   File: kakeup.py    (license) View Source Project 6 votes vote down vote up
def main():
    args = __getopt()
    args.port = DEFAULT_PORT if args.port == None else int(args.port)

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        sock.bind((HOST, args.port))
    except socket.error as msg:
        print ('Cannot create socket. Error: ' + str(msg[0]) + ') Message:' + str(msg[1]))
        sys.exit()

    __handle_sigs_for(sock)

    wol_found = False
    while True:
        packet = sock.recv(65565)

        if (__wol_pktcheck(packet, args.macaddr, args.ipsrc, args.port)
                and not wol_found):
            print("Kore: <WakeUp>")
            os.system(args.cmd)
            wol_found = True
        else:
            wol_found = False 
Example 29
Project: PyQYT   Author: collinsctk   File: PING_RAW.py    (license) View Source Project 6 votes vote down vote up
def ping_one_raw(dst,seq_no):
	send_time = time.time() #????1462346467.457762
	time_in_bytes = struct.pack('d',send_time)
	#?????2???d?8?????????????????????????????????????
	my_checksum = 0
	header = struct.pack('bbHHH', 8, 0, my_checksum, (os.getpid() & 0xffff), int(seq_no))#?????0????????
	#??????????????????????????????????
	payload = struct.pack('18s', b'welcome to qytang!')#?????????????
	#??????????????????????????????????
	my_checksum = do_checksum(header + time_in_bytes + payload)#???????????????????
	#??????????????????????????????????
	icmp_id = (os.getpid() & 0xffff)#????ID???ICMP ECHO?ID
	header = struct.pack('bbHHH', 8, 0, int(my_checksum), icmp_id, int(seq_no))#?????????????????ICMP??
	packet = header + time_in_bytes + payload#???????????????????????
	sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, 1)#??socket???1??icmp??
	sock.sendto(packet, (dst, 1))#??ICMP????????????socket???????????????????
	recv_packet, addr = sock.recvfrom(1024)#?????
	receive_time = time.time()#???????????
	header = struct.unpack('bbHHH',recv_packet[20:28])#??ICMP???
	if header[3] == icmp_id and header[4] == seq_no:#??ICMP ID????????
		echo_request_sendtime = struct.unpack('d',recv_packet[28:36])#?????
		time_to_pass_ms = (receive_time - echo_request_sendtime[0]) * 1000#???????????
		print('Echo Reply Received time=%4.2f ms' % time_to_pass_ms)#????
	else:
		print('.', flush=True)#??????'.' 
Example 30
Project: Malware   Author: vduddu   File: ethernet_sniffer.py    (license) View Source Project 6 votes vote down vote up
def main():
	connection=socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
	while True:
		raw_data,addr=connection.recvfrom(65536)
		dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
		print('\nEthernet Frame:')
		print(TAB_1+'Destination: {}, Source: {}, Protocol: {}'.format(dest_mac,src_mac,eth_proto))

		if eth_proto==8:
			(version,header_length,ttl,proto,src,target,data)=ipv4_packet(data)
			print(TAB_1+'IPv4 Packet:')
			print(TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format(version,header_length,ttl))
            print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format(proto, src, target))

		elif eth_proto==1:
			 icmp = ICMP(ipv4.data) 
Example 31
Project: amadash   Author: ipartola   File: sniffer.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SocketSniffer, self).__init__(*args, **kwargs)
        try:
            self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
            if self.interface:
                self.sock.bind((self.interface, ETH_P_ALL))
        except Exception as e:
            abort('Socket could not be created: {}'.format(e)) 
Example 32
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
Example 33
Project: RSPET   Author: panagiks   File: rspet_client.py    (MIT License) View Source Project 5 votes vote down vote up
def udp_spoof_start(target_ip, target_port, spoofed_ip, spoofed_port, payload):
    """Spoof a packet and send it to target_ip, target_port.

    Keyword argument(s):
    target_ip -- the desired destination ip
    target_port -- the desired destination port
    spoofed_ip -- the desired source ip
    spoofed_port -- the desired source port
    """
    spoofed_packet = udp_spoof_pck(target_ip, target_port, spoofed_ip,
                                   spoofed_port, payload)
    sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)
    while True:
        sock.sendto(spoofed_packet, (target_ip, target_port))
        sleep(0.01) 
Example 34
Project: Static-UPnP   Author: nigelb   File: upnp_reciever.py    (license) View Source Project 5 votes vote down vote up
def setup_sockets(self):
        self.raw_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.raw_sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
        self.raw_sock.bind((self.interface, 0)) 
Example 35
Project: CyberScan   Author: medbenali   File: supersocket.py    (license) View Source Project 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 36
Project: CyberScan   Author: medbenali   File: linux.py    (license) View Source Project 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 37
Project: CyberScan   Author: medbenali   File: linux.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        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 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.bind((iface, type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example 38
Project: CyberScan   Author: medbenali   File: linux.py    (license) View Source Project 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 39
Project: CyberScan   Author: medbenali   File: bluetooth.py    (license) View Source Project 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 40
Project: CyberScan   Author: medbenali   File: inet6.py    (license) View Source Project 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 41
Project: hostapd-mana   Author: adde88   File: supersocket.py    (license) View Source Project 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 42
Project: hostapd-mana   Author: adde88   File: linux.py    (license) View Source Project 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 43
Project: hostapd-mana   Author: adde88   File: linux.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        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 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.bind((iface, type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example 44
Project: hostapd-mana   Author: adde88   File: linux.py    (license) View Source Project 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 45
Project: hostapd-mana   Author: adde88   File: bluetooth.py    (license) View Source Project 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 46
Project: hostapd-mana   Author: adde88   File: inet6.py    (license) View Source Project 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 47
Project: do-latency   Author: dizballanze   File: pyping.py    (license) View Source Project 5 votes vote down vote up
def ping(host, timeout=2, ping_id=None, udp=False):
    """Ping remote host.

    :param str host: Host name/address.
    :param float timeout: timeout.
    :param int ping_id: 16 bit integer to identify packet.
    """
    dest_addr = socket.gethostbyname(host)
    icmp = socket.getprotobyname('icmp')
    socket_type = socket.SOCK_DGRAM if udp else socket.SOCK_RAW
    raw_socket = socket.socket(socket.AF_INET, socket_type, icmp)

    ping_id = os.getpid() if ping_id is None else ping_id
    ping_id &= 0xffff

    seq_code = random.randint(1, 65535)

    latency = None

    start_ts = time.time()
    end_ts = start_ts + timeout

    send_ping(raw_socket, dest_addr, ping_id, seq_code)

    while time.time() < end_ts:
        r_ping_id, r_seq_code, r_recv_ts = receive_reply(raw_socket, timeout)
        if ping_id == r_ping_id and r_seq_code == seq_code:
            latency = r_recv_ts - start_ts
            break

    return latency 
Example 48
Project: NodePingManage   Author: hongfeioo   File: ping.py    (license) View Source Project 5 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

    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

#change this function
#20170413 [email protected] 
Example 49
Project: dash-button   Author: misc0110   File: listen.py    (license) View Source Project 5 votes vote down vote up
def listen():
    last_tid = {}
    rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
    while True:
        packet = rawSocket.recvfrom(2048)
        ethernet_header = struct.unpack("!6s6s2s", packet[0][0:14])
        
        if ethernet_header[2] != '\x08\00':
            continue # not ip
        
        ip_header = struct.unpack("!1s1s2s2s1s1s1s1s2s4s4s", packet[0][14:34])
        
        if ip_header[7] != '\x11':
            continue # not udp

        if len(packet[0][42:]) < 240:
            continue # not dhcp
        
        dhcp_header = struct.unpack("!1s1s1s1s4s2s2s4s4s4s4s6s10s64s128s4s", packet[0][42:282])

        for b in buttons.keys():
            if b in binascii.hexlify(ethernet_header[1]) and b in binascii.hexlify(dhcp_header[11]):
                # filter duplicate presses
                tid = binascii.hexlify(dhcp_header[4])
                if b in last_tid and last_tid[b] == tid:
                    continue
                last_tid[b] = tid
                buttons[b](":".join([b[i:i+2] for i in range(0, len(b), 2)])) 
Example 50
Project: packet-queue   Author: google   File: libnetfilter_queue.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
    self.handle = nfq.nfq_open()
    self.fileno = nfq.nfq_fd(self.handle)
    self.socket = socket.fromfd(self.fileno, socket.AF_UNIX, socket.SOCK_RAW)

    if nfq.nfq_unbind_pf(self.handle, socket.AF_INET) < 0:
      raise OSError('nfq_unbind_pf() failed. Are you root?')

    if nfq.nfq_bind_pf(self.handle, socket.AF_INET) < 0:
      raise OSError('nfq_bind_pf() failed. Are you root?')