Python socket.htons() Examples

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

Example 1
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 2
Project: RSPET   Author: panagiks   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, srcp, dstp):
        self.srcp = srcp
        self.dstp = dstp
        self.seqn = 10
        self.ackn = 0
        self.offset = 5 # Data offset: 5x4 = 20 bytes
        self.reserved = 0
        self.urg = 0
        self.ack = 0
        self.psh = 0
        self.rst = 0
        self.syn = 1
        self.fin = 0
        self.window = socket.htons(5840)
        self.checksum = 0
        self.urgp = 0
        self.payload = "" 
Example 3
Project: CyberScan   Author: medbenali   File: linux.py    (license) View Source Project 6 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 4
Project: NodePingManage   Author: hongfeioo   File: ping.py    (license) View Source Project 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 5
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 3_2_ping_remote_host.py    (license) View Source Project 6 votes vote down vote up
def send_ping(self, sock,  ID):
        """
        Send ping to the target host
        """
        target_addr  =  socket.gethostbyname(self.target_host)
     
        my_checksum = 0
     
        # Create a dummy heder with a 0 checksum.
        header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
        bytes_In_double = struct.calcsize("d")
        data = (192 - bytes_In_double) * "Q"
        data = struct.pack("d", time.time()) + bytes(data.encode('utf-8'))
     
        # Get the checksum on the data and the dummy header.
        my_checksum = self.do_checksum(header + data)
        header = struct.pack(
            "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
        )
        packet = header + data
        sock.sendto(packet, (target_addr, 1)) 
Example 6
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 7
Project: zambie   Author: zanyarjamal   File: pinject.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, srcp, dstp):
        self.srcp = srcp
        self.dstp = dstp
        self.seqn = 10
        self.ackn = 0
        self.offset = 5 # Data offset: 5x4 = 20 bytes
        self.reserved = 0
        self.urg = 0
        self.ack = 0
        self.psh = 0
        self.rst = 0
        self.syn = 1
        self.fin = 0
        self.window = socket.htons(5840)
        self.checksum = 0
        self.urgp = 0
        self.payload = "" 
Example 8
Project: isf   Author: w3h   File: icmp_ping.py    (license) View Source Project 6 votes vote down vote up
def send_ping(self, sock,  ID):
        """
        Send ping to the target host
        """
        target_addr  =  socket.gethostbyname(self.target_host)
     
        my_checksum = 0
     
        # Create a dummy heder with a 0 checksum.
        header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
        bytes_In_double = struct.calcsize("d")
        data = (192 - bytes_In_double) * "Q"
        data = struct.pack("d", time.time()) + data
     
        # Get the checksum on the data and the dummy header.
        my_checksum = self.do_checksum(header + data)
        header = struct.pack(
            "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
        )
        packet = header + data
        sock.sendto(packet, (target_addr, 1)) 
Example 9
Project: raw-packet   Author: Vladimir-Ivanov-Git   File: network.py    (license) View Source Project 6 votes vote down vote up
def make_header(self, source_ip, destination_ip, data_len, transport_protocol_len, transport_protocol, ttl=64):
        srcip = inet_aton(source_ip)       # Source port
        dstip = inet_aton(destination_ip)  # Destination port
        ver = 4       # IP protocol version
        ihl = 5       # Internet Header Length
        dscp_ecn = 0  # Differentiated Services Code Point and Explicit Congestion Notification

        tlen = data_len + transport_protocol_len + 20  # Packet length
        ident = htons(randint(1, 65535))  # Identification
        flg_frgoff = 0  # Flags and fragmentation offset
        ptcl = transport_protocol  # Protocol
        chksm = 0  # Checksum

        ip_header = pack("!" "2B" "3H" "2B" "H" "4s" "4s",
                         (ver << 4) + ihl, dscp_ecn, tlen, ident,
                         flg_frgoff, ttl, ptcl, chksm, srcip, dstip)
        chksm = self.checksum(ip_header)
        return pack("!" "2B" "3H" "2B" "H" "4s" "4s",
                    (ver << 4) + ihl, dscp_ecn, tlen, ident,
                    flg_frgoff, ttl, ptcl, chksm, srcip, dstip) 
Example 10
Project: g3ar   Author: VillanCh   File: ping.py    (license) View Source Project 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 11
Project: g3ar   Author: VillanCh   File: ping.py    (license) View Source Project 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 12
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 13
Project: py-sys   Author: vicky-tan   File: ping_icmp.py    (license) View Source Project 6 votes vote down vote up
def __send_icmp_request(self, icmp_socket, dest_addr, packet_id, sequence):
        
        # ICMP Header :
        # -------------------------------------------------------------------
        # | type(8) | code(8) | checksum(16) | packet_id(16) | sequence(16) |
        # -------------------------------------------------------------------
        #
        packet_checksum = 0
     
        header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, packet_checksum, packet_id, sequence)
        packet_bytes = struct.calcsize('d')
        
        data = (128 - packet_bytes) * '0'
        data = struct.pack('d', time.time()) + data
     
        packet_checksum = self.__checksum(header + data)
     
        header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, socket.htons(packet_checksum), packet_id, sequence)
        packet = header + data
        icmp_socket.sendto(packet, (dest_addr, 1)) 
Example 14
Project: minihydra   Author: VillanCh   File: ping.py    (license) View Source Project 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 15
Project: kbe_server   Author: xiaohaoppy   File: Machines.py    (license) View Source Project 6 votes vote down vote up
def startServer(self, componentType, cid, gus, targetIP, trycount = 1, timeout = 1):
		"""
		"""
		msg = Define.BytesIO()
		msg.write( struct.pack("=H", MachineInterface_startserver ) ) # command
		msg.write( struct.pack("=H", struct.calcsize("=iiQhH") ) ) # command length
		msg.write( struct.pack("=i", self.uid) )
		msg.write( struct.pack("=i", componentType) )
		msg.write( struct.pack("=Q", cid) )
		msg.write( struct.pack("=h", gus) )
		msg.write( struct.pack("=H", socket.htons(self.replyPort)) ) # reply port

		if trycount <= 0:
			self.send( msg.getvalue(), targetIP )
			self.receiveReply()
		else:
			self.sendAndReceive( msg.getvalue(), targetIP, trycount, timeout ) 
Example 16
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 17
Project: deb-ryu   Author: openstack   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: 011_python_network_programming_cookbook_demo   Author: jerry-0824   File: 03_02_ping_remote_host.py    (license) View Source Project 6 votes vote down vote up
def send_ping(self, sock, ID):
	"""
	Send ping to the target host
	"""
	target_addr = socket.gethostbyname(self.target_host)
		
	my_checksum = 0
	
	# Create a dummy heder with a 0 checksum.
	header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
	bytes_In_double = struct.calcsize("d")
	data = (192 - bytes_In_double) * "Q"
	data = struct.pack("d", time.time()) + data
		
	# Get the Checksum on the data and the dummy header.
	my_checksum = self.do_checksum(header + data)
	header = struct.pack( "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 )
	packet = header + data
	sock.sendto(packet, (target_addr, 1)) 
Example 19
Project: Automation-Framework-for-devices   Author: tok-gogogo   File: ping_class.py    (license) View Source Project 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)
 
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0
 
    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)  #?
    #a1 = struct.unpack("bbHHh",header)    #my test
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", time.time()) + data
 
    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)
 
    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1)
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 20
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 21
Project: abe-bootstrap   Author: TryCoin-Team   File: deserialize.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def parse_CAddress(vds):
  d = {}
  d['nVersion'] = vds.read_int32()
  d['nTime'] = vds.read_uint32()
  d['nServices'] = vds.read_uint64()
  d['pchReserved'] = vds.read_bytes(12)
  d['ip'] = socket.inet_ntoa(vds.read_bytes(4))
  d['port'] = socket.htons(vds.read_uint16())
  return d 
Example 22
Project: abe-bootstrap   Author: TryCoin-Team   File: deserialize.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def parse_CAddress(vds):
  d = {}
  d['nVersion'] = vds.read_int32()
  d['nTime'] = vds.read_uint32()
  d['nServices'] = vds.read_uint64()
  d['pchReserved'] = vds.read_bytes(12)
  d['ip'] = socket.inet_ntoa(vds.read_bytes(4))
  d['port'] = socket.htons(vds.read_uint16())
  return d 
Example 23
Project: RSPET   Author: panagiks   File: __init__.py    (MIT License) View Source Project 5 votes vote down vote up
def pack(self):
        ver_ihl = (self.version << 4) + self.ihl
        flags_offset = (self.flags << 13) + self.offset
        ip_header = struct.pack("!BBHHHBBH4s4s",
                    ver_ihl,
                    self.tos,
                    self.tl,
                    self.id,
                    flags_offset,
                    self.ttl,
                    self.protocol,
                    self.checksum,
                    self.source,
                    self.destination)
        self.checksum = checksum(ip_header)
        ip_header = struct.pack("!BBHHHBBH4s4s",
                    ver_ihl,
                    self.tos,
                    self.tl,
                    self.id,
                    flags_offset,
                    self.ttl,
                    self.protocol,
                    socket.htons(self.checksum),
                    self.source,
                    self.destination)  
        return ip_header 
Example 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
Project: packet_analysis   Author: tanjiti   File: networktools.py    (license) View Source Project 5 votes vote down vote up
def getPortNumNetworkByteOrder(st_host):
    """
    Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.
    :param st_host:
    :return: 80-20480
    """
    try:
        st_host = int(st_host)
        return socket.htons(st_host)
    except Exception as e:
        logging.error("[HostByteOrderPortFalse]: %f %s" % (st_host, repr(e))) 
Example 34
Project: pyng   Author: jdowner   File: core.py    (license) View Source Project 5 votes vote down vote up
def send(sock, addr, id, size, seq=1):
    # Create an echo request
    icmp_type = 8
    icmp_code = 0
    icmp_chksum = 0
    icmp_id = id
    icmp_seq = seq

    header = struct.pack("bbHHh",
            icmp_type, icmp_code, icmp_chksum, icmp_id, icmp_seq)

    # The size of the packet must be large enough to accomodate the header and
    # a timestamp
    if size < struct.calcsize("bbHHhd"):
        raise PacketSizeError()

    # Create a chunk of data that is prepended by a timestamp so that we can
    # determine how long it takes the packet to return.
    timestamp = struct.pack("d", time.time())
    data = timestamp + os.urandom(size - struct.caclsize("bbHHhd"))

    # Now we can figure out the checksum
    icmp_chksum = socket.htons(checksum(header + data))

    # Construct the message using the checksum
    header = struct.pack("bbHHh",
            icmp_type, icmp_code, icmp_chksum, icmp_id, icmp_seq)
    packet = header + data

    # Send the request to the address
    host = socket.gethostbyname(addr)
    sock.sendto(packet, (host, 1)) 
Example 35
Project: CVE-2016-6366   Author: RiskSense-Ops   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)) 
Example 36
Project: CVE-2016-6366   Author: RiskSense-Ops   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: CVE-2016-6366   Author: RiskSense-Ops   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: CVE-2016-6366   Author: RiskSense-Ops   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: CVE-2016-6366   Author: RiskSense-Ops   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 40
Project: captiv8   Author: wraith-wireless   File: collect.py    (license) View Source Project 5 votes vote down vote up
def _setup(self,dev):
        try:
            self._s = socket.socket(socket.AF_PACKET,
                                    socket.SOCK_RAW,
                                    socket.htons(0x0003))
            self._s.bind((dev,0x0003))
        except socket.error as e:
            raise RuntimeError(e) 
Example 41
Project: ARPySnitch   Author: securecurebt5   File: ARPySnitch.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, GW_IP, GW_MAC):
		threading.Thread.__init__(self)
		self.GW_IP = GW_IP
		self.GW_MAC = GW_MAC
		self.arpsock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0806))
#		self.arpsock.settimeout(0.1)
		try:
			self.arpdata = self.arpsock.recv(65535)
		except socket.timeout:
			pass 
Example 42
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 1_5_integer_conversion.py    (license) View Source Project 5 votes vote down vote up
def convert_integer():
    data = 1234
    # 32-bit
    print ("Original: %s => Long  host byte order: %s, Network byte order: %s" %(data, socket.ntohl(data), socket.htonl(data)))
    # 16-bit
    print ("Original: %s => Short  host byte order: %s, Network byte order: %s" %(data, socket.ntohs(data), socket.htons(data))) 
Example 43
Project: hakkuframework   Author: 4shadoww   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 44
Project: hakkuframework   Author: 4shadoww   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)
        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)
        _flush_fd(self.ins)
        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 45
Project: hakkuframework   Author: 4shadoww   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)
        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))
        _flush_fd(self.ins)
        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 46
Project: hakkuframework   Author: 4shadoww   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)
        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)
        _flush_fd(self.ins)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) 
Example 47
Project: hakkuframework   Author: 4shadoww   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 48
Project: moops-public   Author: securitymouse   File: fling.py    (license) View Source Project 5 votes vote down vote up
def bootstrap(self):
        if ((self.__IN__ not in self.itemlist) or
                (self.__OUT__ not in self.itemlist)):
                return

        s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
        s.bind((self[self.__IN__], 0))
        self._in = s

        s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
        r = s.bind((self[self.__OUT__], 0))
        self._out = s 
Example 49
Project: fdslight   Author: fdslight   File: ippkts.py    (license) View Source Project 5 votes vote down vote up
def __calc_udp_csum(saddr, daddr, udp_data, is_ipv6=False):
    size = len(udp_data)
    seq = [
        saddr, daddr, b'\x00\x11',
        utils.number2bytes(size, 2),
        udp_data,
    ]

    if is_ipv6:
        size += 24
    else:
        size += 12

    if 0 != size % 2:
        seq.append(b"\0")
        size += 1

    data = b"".join(seq)
    csum = socket.htons(fn_utils.calc_csum(data, size))

    # csum = __calc_checksum(data, size)
    # import socket
    # print(csum,socket.htons(csum_t))

    if csum == 0: return 0xffff

    return csum 
Example 50
Project: pytestlab   Author: sangoma   File: dhcp.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, ifname):
        self.ifname = ifname
        self.poll = select.epoll()
        self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
                                  socket.htons(pnet.ETH_P_ALL))
        self.poll.register(self.sock, select.POLLIN | select.POLLPRI |
                           select.POLLHUP | select.POLLERR)
        attach_filter(self.sock, bootp_filter())
        self.sock.setblocking(0)
        self.sock.bind((ifname, 3))

        ifreq = get_ifreq(self.sock, ifname)
        self.src = pnet.HWAddress(ifreq[18:24])