• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.ntohl函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: interp

def interp(plugin, nuin):
    family = nuin.value(0)
    res_id = nuin.value(1);
    pattrs = (ctypes.POINTER(mnl.Attr) * (nfqnl.NFQA_MAX + 1)).from_buffer(nuin.value(2))

    ph = pattrs[nfqnl.NFQA_PACKET_HDR].contents.get_payload_as(nfqnl.NfqnlMsgPacketHdr)
    packet_id = socket.ntohl(ph.packet_id)
    log.info("res_id: %d, qid: %d", res_id, packet_id)
    nfq_send_accept(res_id, packet_id)

    if pattrs[nfqnl.NFQA_PAYLOAD]:
        ip = IP(bytes(pattrs[nfqnl.NFQA_PAYLOAD].contents.get_payload_v()))
        log.info(ip.summary())

    if pattrs[nfqnl.NFQA_IFINDEX_INDEV]:
        ifin = pattrs[nfqnl.NFQA_IFINDEX_INDEV].contents.get_u32()
        log.info("indev: %d", socket.ntohl(ifin));
    if pattrs[nfqnl.NFQA_IFINDEX_OUTDEV]:
        ifout = pattrs[nfqnl.NFQA_IFINDEX_OUTDEV].contents.get_u32()
        log.info("outdev: %d", socket.ntohl(ifout));

    if pattrs[nfqnl.NFQA_CT]:
        ct = nfct.Conntrack()
        ct.payload_parse(pattrs[nfqnl.NFQA_CT].contents.get_payload_v(), family)
        s = ct.snprintf(4096, nfct.NFCT_T_UNKNOWN, nfct.NFCT_O_DEFAULT, 0)
        log.info("conntrack: %s", s)

    return nurs.NURS_RET_OK
开发者ID:chamaken,项目名称:nurs,代码行数:28,代码来源:nfq_accept.py


示例2: getRoutes

def getRoutes():
    """Reads the routing table from /proc"""
    routes = []
    
    f=open("/proc/net/route","r")
    for l in f.readlines()[1:]:
        # Parse the line
        iface,network,gateway,flags,x,x,metric,mask,x,x,x = l.split()
        # Parse the flags
        flags = int(flags, 16)
        flag_str = ""
        for flag, char in ROUTE_FLAG_CHARS.items():
            if (flags & flag)==flag:
                flag_str += char
        # Store the values
        route = {}
        route["network"] = formatIP(socket.ntohl(long(network, 16)))
        route["gateway"] = formatIP(socket.ntohl(long(gateway, 16)))
        route["netmask"] = formatIP(socket.ntohl(long(mask, 16)))
        route["iface"] = iface
        route["metric"] = metric
        route["flags"] = flag_str
        routes.append(route)
    f.close()
    
    # Kernel gives us a list sorted by netmask length, sort by prefix
    # as well
    routes.sort(route_cmp)
    
    return routes
开发者ID:libzz,项目名称:amiral,代码行数:30,代码来源:ccsd_common.py


示例3: buildKZorpMessage

        def buildKZorpMessage(self):
		"""<method internal="yes">
                </method>
                """
                messages = []
                flags = 0
                if self.umbrella:
                        flags = kznf.kznfnetlink.KZF_ZONE_UMBRELLA
                
                if self.admin_parent:
                        parent_name = self.admin_parent.name
                else:
                        parent_name = None

                if self.address:
                        address = ntohl(self.address.ip)
                        mask = ntohl(self.address.mask)
                else:
                        address = None
                        mask = None

                messages.append((kznf.kznfnetlink.KZNL_MSG_ADD_ZONE, kznf.kznfnetlink.create_add_zone_msg(self.getName(), flags, address, mask, self.name, parent_name)))

                for i in self.inbound_services.keys():
                        messages.append((kznf.kznfnetlink.KZNL_MSG_ADD_ZONE_SVC_IN, kznf.kznfnetlink.create_add_zone_svc_msg(self.name, i)))
                for i in self.outbound_services.keys():
                        messages.append((kznf.kznfnetlink.KZNL_MSG_ADD_ZONE_SVC_OUT, kznf.kznfnetlink.create_add_zone_svc_msg(self.name, i)))

                return messages
开发者ID:pfeiffersz,项目名称:zorp,代码行数:29,代码来源:Zone.py


示例4: decode_ip_packet

def decode_ip_packet(s):
  d={}
  #---IP Header---
  #d['version']=(ord(s[0]) & 0xf0) >> 4
  #d['header_len']=ord(s[0]) & 0x0f
  #d['tos']=ord(s[1])
  #d['total_len']=socket.ntohs(struct.unpack('H',s[2:4])[0])
  #d['id']=socket.ntohs(struct.unpack('H',s[4:6])[0])
  #d['flags']=(ord(s[6]) & 0xe0) >> 5
  #d['fragment_offset']=socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f)
  #d['ttl']=ord(s[8])
  d['protocol']=ord(s[9])
  #d['checksum']=socket.ntohs(struct.unpack('H',s[10:12])[0])
  d['source_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0])
  d['destination_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0])
  #if d['header_len']>5:
  #  d['options']=s[20:4*(d['header_len']-5)]
  #else:
  #  d['options']=None
  #d['data']=s[4*d['header_len']:]

  #---TCP Header---
  #The difference between ntohs and ntohl is the difference between 16bit and 32bit integers.
  #d['source_port'] = socket.ntohs(struct.unpack('H',s[20:22])[0])
  #d['destination_port'] = socket.ntohs(struct.unpack('H',s[22:24])[0])
  d['sequence_number'] = socket.ntohl(struct.unpack('I',s[24:28])[0])
  d['ack_number'] = socket.ntohl(struct.unpack('I',s[28:32])[0])

  return d
开发者ID:atmouse,项目名称:tcp_bandwidth_tester,代码行数:29,代码来源:sniffer.py


示例5: update

    def update(self, filt=None):
        """update([filter])
Update the RouteTable with current values. If a filter function is supplied
then it will be called with a RouteEntry and must return a true or false value.
If true, the RouterEntry will be included in the table. If false, it will not.
"""
        self._entries = []
        lines = open(FILE).readlines()
        for line in lines[1:]:
            [iface, dest, gateway, flags, refcnt, use, metric, mask,
                mtu, window, irtt] = line.split()
            rt = RouteEntry(iface,
                    Destination=ntohl(int(dest, 16)),
                    Gateway=ntohl(int(gateway, 16)),
                    Flags=RouteFlags(flags),
                    RefCnt=int(refcnt, 16),
                    Use=int(use, 16),
                    Metric=int(metric, 16),
                    Mask=ntohl(int(mask, 16)),
                    MTU=int(mtu, 16),
                    Window=int(window, 16),
                    IRTT=int(irtt, 16))
            if filt:
                if filt(rt):
                    self._entries.append(rt)
            else:
                self._entries.append(rt)
开发者ID:bharathi26,项目名称:pycopia,代码行数:27,代码来源:route.py


示例6: get_full_msg_packet_hdr

def get_full_msg_packet_hdr(nfa):
	pkg_hdr = get_msg_packet_hdr(nfa)
	return {
		'packet_id' : ntohl(pkg_hdr.contents.packet_id),
		'hw_protocol' :  ntohl(pkg_hdr.contents.hw_protocol),
		'hook' : pkg_hdr.contents.hook
	}
开发者ID:BackupGGCode,项目名称:proxyshark,代码行数:7,代码来源:libnetfilter_queue.py


示例7: parse_ir

def parse_ir(data, dlen):
	global last_ir

	stamp   = socket.ntohl(struct.unpack('<L', data[0:4])[0])
	format  = struct.unpack('<B', data[4:5])[0]
	nr_bits = struct.unpack('<B', data[5:6])[0]
	code    = socket.ntohl(struct.unpack('<L', data[6:10])[0])
	
	if code not in IR.codes_debug:
		print('stamp   %d' % stamp)
		print('format  %d' % format)
		print('nr bits %d' % nr_bits)
		print('UNKNOWN ir code %d' % code)
		last_ir = None
		return None

	stress = 0
	if last_ir and last_ir[0] == code:
		# the same key was pressed again. if it was done fast enough,
		# then we *guess* that the user is keeping it pressed, rather
		# than hitting it again real fast. unfortunately the remote
		# doesn't generate key release events.
		#print('Stamp %d, diff %d' % (stamp, stamp - last_ir[1]))
		if stamp - last_ir[1] < 130: # milliseconds
			# the threshold can't be set below 108 which seems to be the
			# rate at which the SB3 generates remote events. at the same
			# time it is quite impossible to manually hit keys faster
			# than once per 140ms, so 130ms should be a good threshold.
			stress = last_ir[2] + 1
		else:
			stress = 0
	last_ir = (code, stamp, stress)
	return Tactile(code, stress)
开发者ID:Mysingen,项目名称:dwite,代码行数:33,代码来源:protocol.py


示例8: decode_ip_packet

def decode_ip_packet(s):
    d                        = {}
    d['version']             = (ord(s[0]) & 0xf0) >> 4
    d['header_len']          = ord(s[0]) & 0x0f
    d['tos']                 = ord(s[1])
    d['total_len']           = socket.ntohs(struct.unpack('H',s[2:4])[0])
    d['id']                  = socket.ntohs(struct.unpack('H',s[4:6])[0])
    d['flags']               = (ord(s[6]) & 0xe0) >> 5
    d['fragment_offset']     = socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f)
    d['ttl']                 = ord(s[8])
    d['protocol']            = ord(s[9])
    d['checksum']            = socket.ntohs(struct.unpack('H',s[10:12])[0])
    d['source_address']      = pcap.ntoa(struct.unpack('i',s[12:16])[0])
    d['destination_address'] = pcap.ntoa(struct.unpack('i',s[16:20])[0])
    if d['header_len'] > 5:
        d['options'] = s[20:4*(d['header_len']-5)]
    else:
        d['options'] = None
    d['data']             = s[4*d['header_len']:]
    d['source_port']      = socket.ntohs(struct.unpack('H',d['data'][0:2])[0])
    d['destination_port'] = socket.ntohs(struct.unpack('H',d['data'][2:4])[0])
    d['seq']              = socket.ntohl(struct.unpack('I',d['data'][4:8])[0])
    d['ack']              = socket.ntohl(struct.unpack('I',d['data'][8:12])[0])
    d['tcp_header_len']   = (ord(d['data'][12]) & 0xf0) >> 4
    d['tcp_bit']          = (ord(d['data'][13]) & 0x3f)
    d['tcp_data']         = d['data'][4*d['tcp_header_len']:]
    return d
开发者ID:ElvisWang,项目名称:tcpxm,代码行数:27,代码来源:tcpxm.py


示例9: decode_tcp_packet

def decode_tcp_packet(s):
    d = {}
    d["sport"] = socket.ntohs(struct.unpack('H',s[0:2])[0])
    d["dport"] = socket.ntohs(struct.unpack('H',s[2:4])[0])
    d["seq"] = socket.ntohl(struct.unpack('I',s[4:8])[0])
    d["acknowlege"] = socket.ntohl(struct.unpack('I',s[8:12])[0])
    d["header_len"] = (ord(s[12]) & 0xf0) >> 4
    d["sign"] = ord(s[13])
    d["URG"] = (ord(s[13]) & 0x20) >> 5
    d["ACK"] = (ord(s[13]) & 0x10) >> 4
    d["PSH"] = (ord(s[13]) & 0x08) >> 3
    d["RST"] = (ord(s[13]) & 0x04) >> 2
    d["SYN"] = (ord(s[13]) & 0x02) >> 1
    d["FIN"] = (ord(s[13]) & 0x01)
    d["window"] = socket.ntohs(struct.unpack('H',s[14:16])[0])
    d["checksum"] = socket.ntohs(socket.ntohs(struct.unpack('H',s[16:18])[0]))
    d["URG_POINT"] = socket.ntohs(struct.unpack('H',s[18:20])[0])
    if d['header_len'] > 5:
       #d['options']=s[20:4*(d['header_len']-5)]
       d["options"] = None
       d["options_kind"] = ord(s[20])
       if d["options_kind"] == 2:
           d["options_mss"] = socket.ntohs(struct.unpack('H',s[22:24])[0])
	   d["options"] = "mss:%d" % d["options_mss"]
       elif d["options_kind"] == 3:
           d["options_windows_factor"] = ord(s[22])
           d["options"] = "window factor:%d" % d["options_windows_factor"]
       elif d["options_kind"] == 8:
           d["options_timestamp"] = socket.ntohl(struct.unpack('I',s[22:26])[0]) 
	   d["options_timestamp_ack"] = socket.ntohl(struct.unpack('I',s[26:30])[0])
           d["options"] = "timestamp:%d	timestamp_ack:%d" %(d["options_timestamp"],d["options_timestamp_ack"])
    else:
       d['options']=None
    d['data'] = s[4*d['header_len']:]
    return d
开发者ID:level077,项目名称:sa-tools,代码行数:35,代码来源:mysql_query_sniff.py


示例10: main

def main():
    threads = int(sys.argv[2])
    timeout = int(sys.argv[3])

    if ',' in sys.argv[1]:
        host_list = sys.argv[1].split(',')
        for host in host_list:
            while(True):
                if activeCount() <= threads:
                    Thread(target=modbus_scan, args=(host, timeout)).start()
                    break
                else:
                    continue

    elif '-' in sys.argv[1]:
        host_list = sys.argv[1].split('-')
        start_ip = socket.ntohl(struct.unpack('I', socket.inet_aton(str(host_list[0])))[0])
        end_ip = socket.ntohl(struct.unpack('I', socket.inet_aton(str(host_list[1])))[0])
        for host in range(start_ip, end_ip + 1):
            host = socket.inet_ntoa(struct.pack('I', socket.htonl(host)))
            while (True):
                if activeCount() <= threads:
                    Thread(target=modbus_scan, args=(host, timeout)).start()
                    break
                else:
                    continue
    else:
        host = sys.argv[1]
        modbus_scan(host, timeout)
    while(True):
        if activeCount() < 2:
            return 1
开发者ID:narata,项目名称:ICSScan,代码行数:32,代码来源:modbus.py


示例11: pb2dict

def pb2dict(pb, pretty = False, is_hex = False):
	"""
	Convert protobuf msg to dictionary.
	Takes a protobuf message and returns a dict.
	"""
	d = collections.OrderedDict() if pretty else {}
	for field, value in pb.ListFields():
		if field.label == FD.LABEL_REPEATED:
			d_val = []
			if pretty and _marked_as_ip(field):
				if len(value) == 1:
					v = socket.ntohl(value[0])
					addr = ipaddr.IPv4Address(v)
				else:
					v = 0 +	(socket.ntohl(value[0]) << (32 * 3)) + \
						(socket.ntohl(value[1]) << (32 * 2)) + \
						(socket.ntohl(value[2]) << (32 * 1)) + \
						(socket.ntohl(value[3]))
					addr = ipaddr.IPv6Address(v)

				d_val.append(addr.compressed)
			else:
				for v in value:
					d_val.append(_pb2dict_cast(field, v, pretty, is_hex))
		else:
			d_val = _pb2dict_cast(field, value, pretty, is_hex)

		d[field.name] = d_val
	return d
开发者ID:mainboy,项目名称:criu-alma,代码行数:29,代码来源:pb2dict.py


示例12: random_ipv4

 def random_ipv4(cls, val_range):
     '''
     This returns a IPv4 address in the range
     '''
     ipmin, ipmax = cls.get_ipv4_range_as_int(val_range)
     iprand = socket.htonl(random.randint(socket.ntohl(ipmin), socket.ntohl(ipmax)))
     return socket.inet_ntop(socket.AF_INET, struct.pack('I',iprand))
开发者ID:bigclouds,项目名称:opendove,代码行数:7,代码来源:__init__.py


示例13: DecodeWin7

def DecodeWin7(values, verbose=False):
    ignoreTypes = list()
    if not verbose:
        ignoreTypes.append('UEME_CTLSESSION')
        ignoreTypes.append('UEME_CTLCUACount')
    i = 0
    while i < len(values):
        dsz.script.CheckStop()
        try:
            name = dsz.cmd.data.ObjectGet(values[i], 'Name', dsz.TYPE_STRING)
            value = dsz.cmd.data.ObjectGet(values[i], 'Value', dsz.TYPE_STRING)
            type = dsz.cmd.data.ObjectGet(values[i], 'Type', dsz.TYPE_STRING)
            j = 0
            while j < len(name):
                decodedName = rot13decode(name[j])
                if decodedName.startswith('UEME_'):
                    nameParts = decodedName.split(':', 1)
                else:
                    nameParts = [
                     'UEME_RUNPATH', decodedName]
                ignore = False
                for ignored in ignoreTypes:
                    if nameParts[0] == ignored:
                        ignore = True
                        break

                dsz.script.data.Start('Value')
                dsz.script.data.Add('Type', nameParts[0], dsz.TYPE_STRING)
                if len(nameParts) > 1:
                    nameParts[1] = translateKnownFolders(nameParts[1])
                    dsz.script.data.Add('Data', nameParts[1], dsz.TYPE_STRING)
                if not ignore:
                    dsz.ui.Echo('%s' % nameParts[0])
                    if len(nameParts) > 1:
                        dsz.ui.Echo('      Data : %s' % nameParts[1])
                if type[j] == 'REG_BINARY':
                    if len(value[j]) == 144:
                        count = socket.ntohl(int(value[j][8:16], 16))
                        timestamp2 = socket.ntohl(int(value[j][120:128], 16))
                        timestamp1 = socket.ntohl(int(value[j][128:136], 16))
                        timestamp = long('%08x%08x' % (timestamp1, timestamp2), 16)
                        dsz.script.data.Add('Count', '%u' % count, dsz.TYPE_INT)
                        if not ignore:
                            dsz.ui.Echo('     Count : %u' % count)
                        if timestamp > 0:
                            timestamp /= 10000000
                            timestamp -= 11644473600L
                            t = datetime.datetime.utcfromtimestamp(timestamp)
                            dsz.script.data.Add('Timestamp', t.ctime(), dsz.TYPE_STRING)
                            if not ignore:
                                dsz.ui.Echo(' Last Used : %s' % t.ctime())
                dsz.script.data.End()
                j += 1

        except:
            pass

        i += 1

    return True
开发者ID:ExpLife0011,项目名称:DanderSpritz_docs,代码行数:60,代码来源:_UserAssist.py


示例14: BuildHostRange

def BuildHostRange(strHost):
    slash=[]                                      
    startIpStr=""
    endIpStr=""
    ranges=0
    submask=0

    realStartIP=0
    realEndIP=0

    if strHost.find('-')>0:
        slash = strHost.split('-')
        startIpStr=slash[0]
        endIpStr=slash[1]
    else:
        startIpStr=strHost
    try:
        startIpStr=socket.gethostbyname(startIpStr)
        if strHost.find('-')>0:
            realStartIP = socket.ntohl(struct.unpack('I',socket.inet_aton(startIpStr))[0])
            realEndIP = socket.ntohl(struct.unpack('I',socket.inet_aton(endIpStr))[0])
        else:
            realStartIP=realEndIP=socket.ntohl(struct.unpack('I',socket.inet_aton(startIpStr))[0])
    except:
        return [0,0]

    return [realStartIP,realEndIP]
开发者ID:Mark-Shine,项目名称:station,代码行数:27,代码来源:bing.py


示例15: gen_ip_by_range

 def gen_ip_by_range(seg):
     seg_lst = seg.split('-')
     ip_start = seg_lst[0].strip()
     ip_end = seg_lst[1].strip()
     start = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip_start)))[0])
     end = socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip_end)))[0])
     for key in xrange(end - start + 1):
         yield socket.inet_ntoa(struct.pack('I', socket.htonl(start + key)))
开发者ID:shadowmydx,项目名称:google-ip-searcher,代码行数:8,代码来源:FileGenerator.py


示例16: parse_message_reject

 def parse_message_reject(self, stream, n, length):
     index = ntohl(struct.unpack('I', stream[n+5:n+9])[0])
     begin = ntohl(struct.unpack('I', stream[n+9:n+13])[0])
     length = ntohl(struct.unpack('I', stream[n+13:n+17])[0])
     self.logger.info(
         '[MESSAGE] REJECT: index={} begin={} length={}'.format(
             index, begin, length))
     self.__new_message('reject')
开发者ID:wjianwei126,项目名称:bttools,代码行数:8,代码来源:btparser.py


示例17: parse_message_choke

 def parse_message_choke(self, stream, n, length):
     index = ntohl(struct.unpack('I', stream[n+5:n+9])[0])
     begin = ntohl(struct.unpack('I', stream[n+9:n+13])[0])
     length = ntohl(struct.unpack('I', stream[n+13:n+17])[0])
     self.logger.info(
         '[MESSAGE] CANCEL: index={} begin={} length={}'.format(
             index, begin, length))
     self.__new_message('cancel', index=index, begin=begin, length=length)
开发者ID:wjianwei126,项目名称:bttools,代码行数:8,代码来源:btparser.py


示例18: find

	def find(self,ip,ovs_info):
		int_ip = socket.ntohl(struct.unpack('i',socket.inet_aton(ip))[0])
		for ovs in ovs_info:
			start = socket.ntohl(struct.unpack('i',socket.inet_aton(ovs['OVS_Start_Ip']))[0])
			end = socket.ntohl(struct.unpack('i',socket.inet_aton(ovs['OVS_End_Ip']))[0])
			if start <= int_ip and int_ip >= end:
				return ovs
		return None
开发者ID:liguoyu1,项目名称:python,代码行数:8,代码来源:BuiltTopo.py


示例19: convert_integer

def convert_integer():
    data = 1234;
    #32bit
    print "Original: %s => Long host byte order: %s, Network byte order: %s" \
        %(data, socket.ntohl(data), socket.htonl(data))
    #16bit
    print "Original: %s => Short host bype order: %s, Network byte order: %s" \
        %(data, socket.ntohl(data), socket.htonl(data))
开发者ID:daiyadong,项目名称:python_network_programming,代码行数:8,代码来源:1_5_integer_conversion.py


示例20: _GetS64

def _GetS64(demarsh):
    import socket
    val1 = socket.ntohl(demarsh.GetU32())
    val2 = socket.ntohl(demarsh.GetU32())
    fullVal = val2 << 32 | val1
    if fullVal & 9223372036854775808:
        fullVal = (fullVal & 9223372036854775807) - 9223372036854775808
    return fullVal
开发者ID:chubang122,项目名称:shadowbroker,代码行数:8,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.ntohs函数代码示例发布时间:2022-05-27
下一篇:
Python socket.makefile函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap