当前位置: 首页>>代码示例>>Python>>正文


Python socket.ntohs函数代码示例

本文整理汇总了Python中socket.ntohs函数的典型用法代码示例。如果您正苦于以下问题:Python ntohs函数的具体用法?Python ntohs怎么用?Python ntohs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ntohs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

 def __init__(self, buildstruct=None):
     self.fields = (("OF_IN_PORT","H"),
         ("OF_DL_SRC","B" * 6),
         ("OF_DL_DST","B" * 6),
         ("OF_VLAN_ID", "H"),
         ("OF_VLAN_PCP", "B"),
         ("OF_DL_TYPE", "H"),
         ("OF_NW_TOS", "B"),
         ("OF_NW_PROTO", "B"),
         ("OF_NW_SRC", "I"),
         ("OF_NW_DST", "I"),
         ("OF_TP_SRC", "H"),
         ("OF_TP_DST", "H"),
         ("OF_PADDING", "BBB"),
         )
     self.packed = struct.Struct("!" + "".join(x[1] for x in self.fields))
     if buildstruct is not None:
         self.unpacked = [x for x in self.packed.unpack(buildstruct)]
         self.OF_IN_PORT = ntohs(self.unpacked[0])
         self.OF_DL_SRC = tuple(hex(i) for i in self.unpacked[1:7])[::-1]
         self.OF_DL_DST = tuple(hex(i) for i in self.unpacked[7:13])[::-1]
         self.OF_VLAN_ID = hex(ntohs(self.unpacked[13]))
         self.OF_VLAN_PCP = hex(self.unpacked[14])
         self.OF_DL_TYPE = hex(ntohs(self.unpacked[15]))
         self.OF_NW_TOS = hex(self.unpacked[16])
         self.OF_NW_PROTO = hex(self.unpacked[17])
         self.OF_NW_SRC = inet_ntoa(struct.pack("I", self.unpacked[18]))
         self.OF_NW_DST = inet_ntoa(struct.pack("I", self.unpacked[19]))
         self.OF_TP_SRC = ntohs(self.unpacked[20])
         self.OF_TP_DST = ntohs(self.unpacked[21])
         self.OF_PADDING = ""
开发者ID:Caustic,项目名称:netfpga,代码行数:31,代码来源:of_header.py

示例2: retrieve_the_list_of_peers

    def retrieve_the_list_of_peers(self, splitter_socket, team_socket):
        # {{{

        # The list of peers should be retrieved from the splitter in a
        # different thread because in this way, if the retrieving
        # takes a long time, the peer can receive the chunks that
        # other peers are sending to it.

        sys.stdout.write(Color.green)
        print splitter_socket.getsockname(), "\b: requesting the list of peers to", splitter_socket.getpeername()
        number_of_peers = socket.ntohs(struct.unpack("H",splitter_socket.recv(struct.calcsize("H")))[0])
        print splitter_socket.getpeername(), "\b: the size of the list of peers is", number_of_peers

        while number_of_peers > 0:
            message = splitter_socket.recv(struct.calcsize("4sH"))
            IP_addr, port = struct.unpack("4sH", message)
            IP_addr = socket.inet_ntoa(IP_addr)
            port = socket.ntohs(port)
            peer = (IP_addr, port)
            print "[%5d]" % number_of_peers, peer
            self.peer_list.append(peer)
            self.losses[peer] = 0
            #print Color.green, cluster_socket.getsockname(), \
            #    "-", '"hello"', "->", peer, Color.none
            # Say hello to the peer
            team_socket.sendto('', peer) # Send a empty chunk (this should be fast).
            number_of_peers -= 1

        print 'done'
        sys.stdout.write(Color.none)
开发者ID:prudhvid,项目名称:p2psp-webrtc-experiments,代码行数:30,代码来源:peer_crs.py

示例3: handle

    def handle(self):
        self.logger.debug('handle')

        try:
            msg_header = self.request.recv(4)

            amount_received = len(msg_header)
            unpacked_header = unpack('HH', msg_header)

            amount_expected = socket.ntohs(unpacked_header[0])
            self.req_type = socket.ntohs(unpacked_header[1])

            self.msg_body = ''
            while amount_received < amount_expected:
                self.msg_body += self.request.recv(16384)
                amount_received = len(msg_header) + len(self.msg_body)

        except:
            print 'Unexpected error:', sys.exc_info()[0]
            self.response = self.error()
            self.request.send(self.response)
            return

        RPC_handler = self.RPCs[self.req_type]
        RPC_handler()

        if self.response is not None:
            self.request.send(self.response)

        self.request.close()
开发者ID:nnedkov,项目名称:KademliaDHT,代码行数:30,代码来源:dht_api_server.py

示例4: DecodeMsgHead_Gate

def DecodeMsgHead_Gate(buf):
    headsize = calcsize('0H H H')
    if len(buf) < headsize:
        return 0,0,0
    head = unpack("0H H H", buf[:headsize])
    head = [socket.ntohs(head[1]), socket.ntohs(head[0]) - 4, ]
    return head + [headsize,]
开发者ID:tsrmtrue,项目名称:easy_game_server,代码行数:7,代码来源:coder_hlp_lib.py

示例5: __init__

    def __init__(self, packet):
        # Use ImpactDecoder to reconstruct the packet hierarchy.
        rip = ImpactDecoder.IPDecoder().decode(packet)
        # Extract the ICMP packet from its container (the IP packet).
        ricmp = rip.child()

        self.replyType = ricmp.get_icmp_type()
        self.srcIp = rip.get_ip_src()
        self.dstIp = rip.get_ip_dst()
        self.valid = True
        self.recv_ttl = rip.get_ip_ttl()

        if ricmp.ICMP_ECHOREPLY == self.replyType:
            data = ricmp.get_data_as_string()
            self.endnodeId = socket.ntohs(struct.unpack('H',data[4:6])[0])
            self.hopNr = socket.ntohs(struct.unpack('H',data[6:8])[0])

        elif (ricmp.ICMP_UNREACH == self.replyType) or (ricmp.ICMP_TIMXCEED == self.replyType):
            data = ricmp.get_data_as_string()
            if len(data) < (36-8):
                self.valid = False
                return
            self.endnodeId = socket.ntohs(struct.unpack('H',data[(32-8):(34-8)])[0])
            self.hopNr = socket.ntohs(struct.unpack('H',data[(34-8):(36-8)])[0])

        else:
            self.valid = False
开发者ID:xychix,项目名称:gtrcrt,代码行数:27,代码来源:sendPacket.py

示例6: run

    def run(self):

        # Request the list of peers.
        sys.stdout.write(Color.green)
        print splitter_socket.getsockname(), "\b: requesting the list of peers to", splitter_socket.getpeername()

        number_of_peers = socket.ntohs(struct.unpack("H",splitter_socket.recv(struct.calcsize("H")))[0])

        print splitter_socket.getpeername(), "\b: the size of the list of peers is", number_of_peers

        while number_of_peers > 0:
            message = splitter_socket.recv(struct.calcsize("4sH"))
            IP_addr, port = struct.unpack("4sH", message)
            IP_addr = socket.inet_ntoa(IP_addr)
            port = socket.ntohs(port)
            peer = (IP_addr, port)

            print "[%5d]" % number_of_peers, peer

            peer_list.append(peer)
            unreliability[peer] = 0
            #print Color.green, cluster_socket.getsockname(), \
            #    "-", '"hello"', "->", peer, Color.none
            # Say hello to the peer
            cluster_socket.sendto('', peer) # Send a empty chunk (this
                                          # should be fast).
            number_of_peers -= 1

        print 'done'
        sys.stdout.write(Color.none)
开发者ID:prudhvid,项目名称:p2psp-webrtc-experiments,代码行数:30,代码来源:peer_v1.py

示例7: __init__

 def __init__(self):
     #
     # init RAW ethernet socket for ARP
     self.sk_arp = socket(AF_PACKET, SOCK_RAW, ntohs(0x0806))
     self.sk_arp.settimeout(0.1)
     #self.sk_arp.setsockopt(SOL_PACKET, SO_RCVBUF, 0)
     self.sk_arp.bind((self.GGSN_ETH_IF, 0x0806))
     #self.sk_arp.setsockopt(SOL_PACKET, SO_RCVBUF, 2**24)
     #
     # init RAW ethernet socket for IPv4
     self.sk_ip = socket(AF_PACKET, SOCK_RAW, ntohs(0x0800))
     self.sk_ip.settimeout(0.1)
     #self.sk_ip.setsockopt(SOL_PACKET, SO_RCVBUF, 0)
     self.sk_ip.bind((self.GGSN_ETH_IF, 0x0800))
     #self.sk_ip.setsockopt(SOL_PACKET, SO_RCVBUF, 2**24)
     #
     # ARP resolution table
     self.ARP_RESOLV_TABLE = {
         self.ROUTER_IP_ADDR : self.ROUTER_MAC_ADDR,
         self.GGSN_IP_ADDR : self.GGSN_MAC_ADDR,
         }
     for ip in self.IP_POOL:
         self.ARP_RESOLV_TABLE[ip] = self.GGSN_MAC_ADDR
     #
     # interrupt handler
     #def sigint_handler(signum, frame):
     #    if self.DEBUG > 1:
     #        self._log('CTRL+C caught')
     #    self.stop()
     #signal.signal(signal.SIGINT, sigint_handler)
     #
     # starting main listening loop in background
     self._listening = True
     self._listener_t = threadit(self.listen)
     self._log('ARP resolver started')
开发者ID:amanone,项目名称:libmich,代码行数:35,代码来源:GTPmgr.py

示例8: data_to_qos_filter

 def data_to_qos_filter(self, data):
     qos_filter = {}
     (
         flags, offshift, nkeys, offmask, off, offoff, hoff, hmask
     ) = struct.unpack('BBBHHhhI', data[:16])
     # offmask and hmask are network/big endian
     offmask = socket.ntohs(offmask)
     hmask = socket.ntohs(hmask)
     for i in range(nkeys):
         p = 16 + i * 16
         # Mask and val are network/big endian
         (mask, val) = struct.unpack('!II', data[p:p+8])
         (off, offmask) = struct.unpack('ii', data[p+8:p+16])
         if off == 8 and mask == 0x00FF0000:
             qos_filter['protocol'] = val
         elif off == 20:
             if mask == 0xFFFF0000:
                 qos_filter['src_port'] = val >> 16
             elif mask == 0x0000FFFF:
                 qos_filter['dst_port'] = val
         elif off == 12:
             address = socket.inet_ntoa(data[p+4:p+8])
             prefix = MASK2PREFIXLEN_MAP[mask]
             qos_filter['src_addr'] = '%s/%s' % (address, prefix)
         elif off == 16:
             address = socket.inet_ntoa(data[p+4:p+8])
             prefix = MASK2PREFIXLEN_MAP[mask]
             qos_filter['dst_addr'] = '%s/%s' % (address, prefix)
     return qos_filter
开发者ID:eayunstack,项目名称:neutron-qos,代码行数:29,代码来源:htb.py

示例9: parse_message

def parse_message(message):
    
    returnVal = {}
    
    # header
    if len(message) < 14:
        raise ValueError(('message to short, {0} bytes: not space for header'.format(len(message))))
    
    header_string = message[:14]
    header = map(ord, header_string)
    returnVal['version'] = (header[0]>>6)&0x03
    if returnVal['version'] != d.VERSION:
        raise e.messageFormatError('invalid version {0}'.format(returnVal['version']))
    
    returnVal['msg_type'] = header[0]&0x3f
    if returnVal['msg_type'] not in d.TYPE_ALL:
        raise e.messageFormatError('invalid message type {0}'.format(returnVal['type']))
    
    returnVal['method'] = header[1]

    returnVal['message_id'] = socket.ntohs(u.buf2int(header[2:4]))

    returnVal['len'] = socket.ntohs(u.buf2int(header[4:6]))

    returnVal['device_id'] = message[6:14]

    if len(message) > 14:
        returnVal['parameters'] = message[14:14 + returnVal['len']]
    else:
        returnVal['parameters'] = []
    
    logging.debug('parsed message: {0}'.format(returnVal))
    
    return returnVal
开发者ID:codartX,项目名称:Coconut,代码行数:34,代码来源:message.py

示例10: _ipv4_decode

    def _ipv4_decode(self, packet_in):
        """Extract the IP header and populate a dictionary of values, returning
        a the dictionary and the remaining data to extract.

        :param str packet_in: The IP packet data
        :returns: tuple

        """
        out = {'version': struct.unpack('b', packet_in[0])[0] >> 4,
               'ihl': (struct.unpack('b', packet_in[0])[0] & 0x0F) * 4,
               'total_length': ntohs(struct.unpack('H', packet_in[2:4])[0]),
               'identification': ntohs(struct.unpack('H', packet_in[4:6])[0]),
               'flags': (ord(packet_in[6]) & 0xe0) >> 5,
               'fragment_offset': (ntohs(struct.unpack('H',
                                                       packet_in[6:8])[0]) &
                                   0x1f),
               'ttl': ord(packet_in[8]),
               'protocol': ord(packet_in[9]),
               'checksum': ntohs(struct.unpack('H', packet_in[10:12])[0]),
               'source': pcap.ntoa(struct.unpack('i', packet_in[12:16])[0]),
               'destination': pcap.ntoa(struct.unpack('i',
                                                      packet_in[16:20])[0])}

        # If our header size is more than 5 bytes, we have options
        if out['ihl'] > _IPV4_BASE_HEADER_SIZE:
            out['options'] = packet_in[_IPV4_BASE_HEADER_SIZE:out['ihl']]
        else:
            out['options'] = None

        # Return the decoded packet
        return out, packet_in[out['ihl']:]
开发者ID:gmr,项目名称:menwith,代码行数:31,代码来源:network.py

示例11: execute

    def execute(self):
        op = self.op
        opts = self.opts

	(profile, addr_space, symtab, types) = linux_load_and_identify_image( \
            self.op, self.opts)

        theProfile = Profile(abstract_types=profile)

        task_list = process_list(addr_space,theProfile.abstract_types, symtab,theProfile)

        for task in task_list:
            comm = read_null_string(addr_space, theProfile.abstract_types,\
                ['task_struct', 'comm'], task.offset)
            process_id = task.pid
            processor = task_cpu(task.thread_info.cpu)

            print "PID: %-5ld  TASK: 0x%x  CPU: %-2s  COMMAND: \"%s\""%(task.pid,task.offset,processor,comm)

            print "%-4s %-10s %-10s %-22s %-7s %-21s %-21s"%('FD','SOCKET','SOCK','FAMILY:TYPE','PROTO', 'SOURCE-PORT', 'DESTINATION-PORT')

            fds = task_fds(task,addr_space, theProfile.abstract_types, symtab, theProfile)
            num_sockets = 0
            for fd, filep, dentry, inode in fds:
               
                socketaddr = self.inode2socketaddr(inode,theProfile)
                if (not socketaddr): continue
                num_sockets += 1
                
                socket = Object('socket', socketaddr, addr_space, \
                     None, theProfile) 
                sock_addr = socket.m('sk').v()
                sock = socket.sk
                skc_prot = sock.get_deep_member(['__sk_common', 'skc_prot']).v()
                skc_family = sock.get_deep_member(['__sk_common', 'skc_family']).v()

                proto_name = ""
                proto_name = read_null_string(addr_space, theProfile.abstract_types,['proto', 'name'], skc_prot)
                sktype = sock.sk_type

                src_and_dst = ""
                src_string = ""
                dst_string =""
                if (PFAMILIES[skc_family] == "PF_INET" or PFAMILIES[skc_family] == "PF_INET6"):
                    sock = Object('inet_sock', sock_addr, addr_space, None, theProfile)
                    src_val = sock.m('rcv_saddr').v()
                    sport = ntohs(sock.m('sport').v())
                    dst_val = sock.m('daddr').v()
                    dport = ntohs(sock.m('dport').v())
                    src_string = self.formatIPv4(src_val,sport)
                    dst_string = self.formatIPv4(dst_val,dport)

                family_type = "%s:%s"%(PFAMILIES[skc_family],sockTypes[sktype])
                print "%-4d 0x%0.8x 0x%0.8x %-22s %-7s %-21s %-21s" % \
		    (fd, socketaddr, sock_addr,family_type, proto_name,\
		    src_string, dst_string)

            if not num_sockets:
                print "No open sockets"
            print
开发者ID:anarchivist,项目名称:pyflag,代码行数:60,代码来源:linsockets.py

示例12: decode

    def decode(self, pktdata):
        if len(pktdata) < 10:
            raise layer.ProtocolMismatch("Not enough data")

        self.hardware_type = socket.ntohs(struct.unpack('H', pktdata[0:2])[0])
        self.protocol_type = socket.ntohs(struct.unpack('H', pktdata[2:4])[0])
        self.hardware_len = (ord(pktdata[4]))
        self.protocol_len = (ord(pktdata[5]))
        # 1: request - 2: reply
        self.operation = socket.ntohs(struct.unpack('H', pktdata[6:8])[0])

        lh = self.hardware_len
        lp = self.protocol_len

        self.mac_src = 0
        self.ip_src = 0

        self.mac_dst = 0
        self.ip_dst = 0

        if lp == 4:
            self.mac_src = pktdata[8:8+lh]
            self.ip_src = struct.unpack('I', pktdata[8+lh:8+lh+lp])[0]

            self.mac_dst = pktdata[8+lh+lp:8+lh+lp+lh]
            self.ip_dst = struct.unpack('I', pktdata[8+lh+lp+lh:8+lh+lp+lh+lp])[0]
        elif lp == 16:
            self.mac_src = pktdata[8:8+lh]
            self.ip_src = struct.unpack('IIII', pktdata[8+lh:8+lh+lp])[0]

            self.mac_dst = pktdata[8+lh+lp:8+lh+lp+lh]
            self.ip_dst = struct.unpack('IIII', pktdata[8+lh+lp+lh:8+lh+lp+lh+lp])[0]
开发者ID:OlivierB,项目名称:Network-Display-On-Pi,代码行数:32,代码来源:arp.py

示例13: __decode_ip

def __decode_ip(s):  
    d={}
    d['order'] = ['version','header_len','dsfield','total_len','id','flags','fragment_offset','time_to_live','protocol','checksum','src_address','dst_address','options','data']
    d['version'] = ((ord(s[0]) & 0xf0) >> 4)
    d['header_len'] = (ord(s[0]) & 0x0f) * 4;
    d['dsfield']= ord(s[1])
    d['total_len']= socket.ntohs(struct.unpack('H',s[2:4])[0])
    d['id']= '0x%.4X' % socket.ntohs(struct.unpack('H',s[4:6])[0])
    d['flags']= '0x%.2X' % ((ord(s[6]) & 0xe0) >> 5)
    d['fragment_offset']= '%d' % socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f)
    d['time_to_live']= '%d' % ord(s[8])
    try:
        d['protocol']= ip_protocols[ord(s[9])]
    except:
        d['protocol']= 'Unknown'
        
    d['checksum']= '0x%.4X' % socket.ntohs(struct.unpack('H',s[10:12])[0])
    d['src_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0])
    d['dst_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0])
    if d['header_len']>20:
        d['options']=s[20:d['header_len']]
    else:
        d['options']=None
    d['data']=('%d bytes %s' % (len(s[d['header_len']:]),PROMPT),s[d['header_len']:])

    return d
开发者ID:sKabYY,项目名称:WireDog,代码行数:26,代码来源:parse.py

示例14: _process

	def _process(self, packet):
		p = packet['data']
		hlen = ord(p[4])
		plen = ord(p[5])

		d = {}
		d['htype'] = socket.ntohs(struct.unpack('H',p[0:2])[0]) 
		d['ptype'] = socket.ntohs(struct.unpack('H',p[2:4])[0])
		d['op'] = socket.ntohs(struct.unpack('H',p[6:8])[0])
		d['op'] = 'request' if d['op']==1 else 'reply' if d['op']==2 else 'unknown'

		i = 8
		d['sha'] = p[i:i+hlen]
		i += hlen
		d['spa'] = p[i:i+plen]
		i += plen
		d['tha'] = p[i:i+hlen]
		i += hlen
		d['tpa'] = p[i:i+plen]

		if (hlen==6) and (plen==4):
			# we'll assume this is ARP for IPv4
			d['sha'] = binascii.hexlify(d['sha'])
			d['tha'] = binascii.hexlify(d['tha'])
			d['spa'] = socket.inet_ntoa(d['spa'])
			d['tpa'] = socket.inet_ntoa(d['tpa'])	

		return d
开发者ID:leandrinux,项目名称:fireherd,代码行数:28,代码来源:arp.py

示例15: __parse_ip_tcp

def __parse_ip_tcp(pkt,s):
    d = {}
    d['order'] = ['src_port','dst_port','seq_number','ack_number','header_len','flags','window_size','checksum','options','data']
    d['src_port'] = socket.ntohs(struct.unpack('H',s[0:2])[0])
    d['dst_port'] = socket.ntohs(struct.unpack('H',s[2:4])[0])
    d['seq_number'] = (struct.unpack('!I',s[4:8])[0])
    d['ack_number'] = (struct.unpack('!I',s[8:12])[0])
    d['header_len'] = ((ord(s[12]) & 0xf0)>>4) * 4;
    pkt.data_len -= d['header_len']
    flags = decode_flag(ord(s[13]))
    d['flags']= '0x%.2X [%s]' % ( ord(s[13]), ','.join(flags) )
    d['window_size'] = socket.ntohs(struct.unpack('H',s[14:16])[0]) * 128
    d['checksum'] = '0x%.4X' % socket.ntohs(struct.unpack('H',s[16:18])[0])
    d['options']=decode_option_tcp(s[20:d['header_len']])
    d['data']=('%d bytes %s' % (len(s[d['header_len']:]), PROMPT), s[d['header_len']:])
    d['info'] = '%s > %s [%s] Seq = %d Len = %d' %(d['src_port'],d['dst_port'],','.join(flags),d['seq_number'],len(d['data'][1]))
    ip = pkt.dict['ip']
    key = __keygen(ip['src_address'],d['src_port'],ip['dst_address'],d['dst_port'])
    pkt.dict.update({'TCP':d})
    if d['data'][1].startswith('HTTP'):
        if stream_pool.has_key(key):
            print "Duplicate stream_pool_key %s" % key
        r = Reassemble(pkt,d)
        if not r.isFinish():
            stream_pool[key] = r
    elif d['data'][1].startswith('GET'):
        if stream_pool.has_key(key):
            print "Duplicate stream_pool_key %s" % key
        r = Reassemble(pkt,d)
        if not r.isFinish():
            stream_pool[key] = r
    else:
        if stream_pool.has_key(key):
            stream_pool[key].addpkt(pkt,d)
            if stream_pool[key].isFinish():
                stream_pool.pop(key)
#    if 'SYN' in flags and not 'ACK' in flags:
#        if stream_pool.has_key(key):
#            print "Duplicate stream_pool_key %s" % key
#            print stream_pool
#            return {'order':[]}
#        stream_pool[key] = PoolEntry(pkt,d,key,flags)
##    elif 'SYN' in flags and 'ACK' in flags:
##        if not stream_pool.has_key(key):
##            print "Lack of stream_pool_key %s" % key
##            print stream_pool
##            stream_pool[key] = PoolEntry(pkt,d,key)
##            return {'order':[]}
##        stream_pool[key].addpkt(pkt,d['seq_number'],d['ack_number'],d['data'],d['header_len'])
##        stream_pool[key].synack(pkt,d)
#    else:
#        if not stream_pool.has_key(key):
#            print "Lack of stream_pool_key %s" % key
#            print stream_pool
#            stream_pool[key] = PoolEntry(pkt,d,key,flags)
#            #return {'order':[]}
#        else:
#            stream_pool[key].addpkt(pkt,d,flags)
#    stream_pool[key].dump()
    return d
开发者ID:sKabYY,项目名称:WireDog,代码行数:60,代码来源:parse.py


注:本文中的socket.ntohs函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。