本文整理汇总了Python中socket.htonl函数的典型用法代码示例。如果您正苦于以下问题:Python htonl函数的具体用法?Python htonl怎么用?Python htonl使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了htonl函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _send_ir
def _send_ir(self, code):
elapsed = time.time() - self._starttime
ticks = long(elapsed * 625000) % 2**32
packet = 'i\x00' + struct.pack('L', socket.htonl(ticks)) + \
'\xff\x10' + struct.pack('L', socket.htonl(code)) + \
''.join(["%c" % i for i in self._mac_addr])
self._send_packet(packet);
示例2: test_client
def test_client():
# 新建socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((args.host, args.port))
md5 = hashlib.md5()
body = ""
with open(args.file, "r+") as log_file:
for f in log_file:
body += f
md5.update(f)
log_length = len(body)
# 构造发送包
package = struct.pack(
"I32s16sI{}s".format(log_length),
socket.htonl(random.choice([101, 104])),
"192.168.1.24.zip",
md5.hexdigest()[:16],
socket.htonl(log_length),
body,
)
s.sendall(package)
s.close()
示例3: openmcastsock
def openmcastsock(group, port):
# Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Allow multiple copies of this program on one machine
# (not strictly needed)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind it to the port
# IRJ -- This needs to be fixed
s.bind(('', port))
# Look up multicast group address in name server
# (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
group = socket.gethostbyname(group)
# Construct binary group address
bytes = map(int, string.split(group, "."))
grpaddr = long(0)
for byte in bytes:
grpaddr = (grpaddr << 8) | byte
# Construct struct mreq from grpaddr and ifaddr
ifaddr = socket.INADDR_ANY
mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr))
# Add group membership
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
return s
示例4: _omc_delta
def _omc_delta(self, key, delta, initial, expiration, timeout, func_name):
# Delta operation definition in the protocol is a bit weird; if
# 'expiration' is set to DELTA_NO_ADD (0xffffffff) the value will
# not be created if it doesn't exist yet, but since we have a
# 'initial' argument in the python api we'd really like to use it to
# signal whether or not a value should be initialized.
#
# To do that we'll map expiration to DELTA_NO_ADD if initial is None
# and expiration is empty and throw an error if initial is None but
# expiration isn't empty.
if delta < 0:
opcode = CMD_DECREMENT
delta = -delta
else:
opcode = CMD_INCREMENT
if initial is None:
if expiration:
raise Error(func_name + " operation's initial must be set if expiration time is used")
expiration = DELTA_NO_ADD
initial = 0
# CFFI doesn't support packed structs before version 0.8.2 so we create
# an array of 5 x uint32_s instead of 2 x uint64_t + 1 x uint32_t
extra = _ffi.new("uint32_t[]", 5)
extra[0] = socket.htonl(delta >> 32)
extra[1] = socket.htonl(delta & 0xffffffff)
if initial:
extra[2] = socket.htonl(initial >> 32)
extra[3] = socket.htonl(initial & 0xffffffff)
extra[4] = socket.htonl(expiration)
req, objs = self._request(opcode, key=_to_bytes(key), extra=extra)
timeout = timeout if timeout is not None else self.io_timeout
resps = self._omc_command_async(req, 1, timeout, func_name)
self._omc_check(resps[0].status, func_name)
return resps[0].delta_value
示例5: _crypt
def _crypt(key, plain):
"""
Crypt plain text with key.
"""
if len(plain) % 8 != 0:
raise ValueError("Length of plain text must be multiple of 8.")
crypted = ""
cycle = [0, 0]
result = [0, 0]
keys = [socket.ntohl(int(s, 16)) for s in struct.unpack("8s" * (len(str(key)) / 8), "%x" % key)]
data = struct.unpack("I" * (len(plain) / 4), plain)
i = 0
while i < len(data):
cycle[0] = data[i] ^ result[0]
cycle[1] = data[i + 1] ^ result[1]
result = _tea_encrypt(cycle, keys)
crypted += "%08x%08x" % (socket.htonl(result[0]) & 0xFFFFFFFFL, socket.htonl(result[1]) & 0xFFFFFFFFL)
i += 2
return crypted
示例6: send_packet_back
def send_packet_back(self):
from socket import htonl
type_map = {
1 : 'app',
2 : 'box',
3 : 'erp',
4 : 'init',
}
cli = 'no type'
if self._device_type in type_map:
cli = type_map[self._device_type]
#!!! put business logic result here
body = 'hi~ %s' % cli
ip = htonl(unpack('I', socket.inet_aton(self._ip))[0])
header = pack("2I32sdII", htonl(self._device_type),
htonl(self._device_id), self._md5, self._timestamp,
htonl(len(body)), ip)
msg = header + body
self._stream.write(msg)
logging.debug('send packet back: header(%d, %d, %s, %.4f, %d, %s) body:%s'
% (self._device_type, self._device_id, self._md5,
self._timestamp, len(body), self._ip, body))
self._stream.read_bytes(BUSINESS_HEADER_LENGTH, self.read_packet_header)
示例7: test_dict
def test_dict(d):
test_attr_rw(d, 'simple_int', 55555, 44444)
test_attr_rw(d, 'literal_int', 66666, 77777)
test_attr_rw(d, 'simple_str', 'abcdef', 'kukutyin1')
test_attr_rw(d, 'literal_str', 'abrakadabra', 'kukutyin2')
test_attr_rw(d, 'simple_cstr', 'huligan', 'kukutyin3')
test_attr_ro(d, 'literal_cstr_ro', 'viharkeszulodik')
test_attr_rw(d, 'literal_cstr', 'viharkeszulodik2', 'kismacska3')
test_attr_rw(d, 'simple_ip', socket.htonl(0xc0a80506), socket.htonl(0xc0a80508))
test_attr_rw(d, 'simple_ip_str', '192.168.5.8', '192.168.8.9')
test_attr_ro(d, 'simple_ip', socket.htonl(0xc0a80809))
test_attr_rw(d, 'alias', 'kukutyin1', 'masvalami')
test_attr_ro(d, 'bytearray_dup', 'bytearray' + '\0' * (128 - len('bytearray')))
test_attr_ro(d, 'bytearray', 'bytearray' + '\0' * (128 - len('bytearray')))
test_sockaddr(d.simple_obj)
if not (d.custom == 0 and d.custom == 1 and d.custom == 2):
raise ValueError
d.custom = 55
if not (d.custom == 0 and d.custom == 1 and d.custom == 2):
raise ValueError
return 1
示例8: lookup
def lookup(self, localport, localip, remoteport, remoteip):
try:
f = file("/proc/net/tcp", "r")
except IOError:
print >> sys.stderr, "Couldn't open /proc/net/tcp"
return None
f.readline()
li = [long(i) for i in localip.split(".")]
localip = (li[0] << 24) + (li[1] << 16) + (li[2] << 8) + li[3]
ri = [long(i) for i in remoteip.split(".")]
remoteip = (ri[0] << 24) + (ri[1] << 16) + (ri[2] << 8) + ri[3]
for l in f.xreadlines():
sp = l.split()
if len(sp) < 8:
continue
locip, locport = sp[1].split(":")
locip = socket.htonl(long(locip, 16)) & 0xFFFFFFFFL
locport = int(locport, 16)
remip, remport = sp[2].split(":")
remip = socket.htonl(long(remip, 16)) & 0xFFFFFFFFL
remport = int(remport, 16)
if (localip, localport, remoteip, remoteport) != (locip, locport, remip, remport):
continue
uid = int(sp[7])
try:
pw = pwd.getpwuid(uid)
return pw[0]
except:
return "ERROR:NO-USER"
return None
示例9: open
def open(self):
# Allow multiple copies of this program on one machine
# (not strictly needed)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind it to the port
self.socket.bind(('', self.port))
# Look up multicast group address in name server
# (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
self.group = socket.gethostbyname(self.group)
# Construct binary group address
bytes = map(int, self.group.split("."))
grpaddr = 0L
for byte in bytes:
grpaddr = (grpaddr << 8) | byte
# Construct struct mreq from grpaddr and ifaddr
ifaddr = socket.INADDR_ANY
mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr))
# Add group membership
self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
mreq)
示例10: get_Unified2IDSEvent
def get_Unified2IDSEvent(data):
'''
//UNIFIED2_IDS_EVENT_VLAN = type 104
//comes from SFDC to EStreamer archive in serialized form with the extended header
typedef struct _Unified2IDSEvent
{
uint32_t sensor_id;
uint32_t event_id;
uint32_t event_second;
uint32_t event_microsecond;
uint32_t signature_id;
uint32_t generator_id;
uint32_t signature_revision;
uint32_t classification_id;
uint32_t priority_id;
uint32_t ip_source;
uint32_t ip_destination;
uint16_t sport_itype;
uint16_t dport_icode;
uint8_t protocol;
uint8_t impact_flag;//overloads packet_action
uint8_t impact;
uint8_t blocked;
uint32_t mpls_label;
uint16_t vlanId;
uint16_t pad2;//Policy ID
} Unified2IDSEvent;
'''
sensor_id, event_id, event_second, event_microsecond, \
signature_id, generator_id, signature_revision, classification_id, \
priority_id, source_ip, destination_ip, sport_itpye, dport_icode, \
protocol, impact_flag, impact, blocked, mpls_label, \
vlanid, pad = struct.unpack("!IIIIIIIIIIIHHBBBBIHH", data)
sip_int = int(source_ip)
dip_int = int(destination_ip)
source_ip_str = socket.inet_ntoa(struct.pack("I", socket.htonl((sip_int))))
dest_ip_str = socket.inet_ntoa(struct.pack("I", socket.htonl((dip_int))))
ev = SnortIDSEvent()
ev["raw_data"] = hexlify(data)
ev["sensor_id"] = sensor_id
ev["event_id"] = event_id
ev["event_second"] = event_second
ev["event_microsecond"] = event_microsecond
ev["signature_id"] = signature_id
ev["generator_id"] = generator_id
ev["signature_revision"] = signature_revision
ev["classification_id"] = classification_id
ev["priority_id"] = priority_id
ev["ip_source"] = source_ip_str
ev["ip_destination"] = dest_ip_str
ev["sport_itype"] = sport_itpye
ev["dport_icode"] = dport_icode
ev["protocol"] = protocol
ev["impact_flag"] = impact_flag
ev["impact"] = impact
ev["blocked"] = blocked
ev["timestamp"] = time()#to detect lapsed events
SnortUnpack.ids_events_lock.acquire()
SnortUnpack.ids_events[event_id] = ev
SnortUnpack.ids_events_lock.release()
示例11: genbuf
def genbuf(buf,index,count):
# Md5
m = md5.new()
m.update(buf)
crc = m.digest()
# encrypt
#buf = genencbuf(buf,genkey())
# calc length
databuf_len = len(buf)
# next pack
next_pack = count
# count
card_count = 2
# pack index
p_index = index
header = pack(SEND_DATA_STRUCT,socket.htonl(databuf_len),
socket.htonl(FUNC_NO),socket.htonl(p_index),
socket.htonl(card_count),socket.htonl(next_pack),0,0)
#data
databuf = header + crc + buf
print binascii.b2a_hex(crc)
# data
print "length of data [%d] : length of buf [%08x] " % (databuf_len , len(databuf))
return databuf
示例12: _openmcastsock
def _openmcastsock(group, port):
"""
Open a UDP socket, bind it to a port and select a multicast group
Borrowed from the Python demos.
"""
#
# Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#
# Allow multiple copies of this program on one machine
# (not strictly needed)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#
# Bind it to the port
s.bind(('', port))
#
# Look up multicast group address in name server
# (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
group = socket.gethostbyname(group)
#
# Construct binary group address
bytes = map(int, group.split("."))
grpaddr = 0
for byte in bytes: grpaddr = (grpaddr << 8) | byte
#
# Construct struct mreq from grpaddr and ifaddr
ifaddr = socket.INADDR_ANY
mreq = struct.pack('ll', socket.htonl(grpaddr), socket.htonl(ifaddr))
#
# Add group membership
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
#
return s
示例13: send
def send(self, body='hi~'):
"""send packet back"""
logging.debug('send packet back: body(%d, %d, %d, %d, %d, %d) %d:%s'
% (self._author, self._version, self._request, self._verify,
self._length, self._device, len(body), body))
from socket import htonl
header1 = pack("6I", htonl(self._author),
htonl(self._version), htonl(self._request),
htonl(self._verify), htonl(self._length),
htonl(self._device))
body = header1 + body
ip = htonl(unpack('I', socket.inet_aton(self._ip))[0])
header = pack("2I32sdII", htonl(self._device_type),
htonl(self._device_id), self._md5, self._timestamp,
htonl(len(body)), ip)
msg = header + body
self._stream.write(msg)
#ip = htonl(socket.inet_aton(self._ip))
ip = 0
logging.debug(ip)
logging.debug('send packet back: header(%d, %d, %s, %.4f, %d, %s)'
% (int(self._device_type), int(self._device_id), self._md5,
self._timestamp, len(body), int(ip)))
示例14: getUPnP
def getUPnP():
"Returns a deferred, which returns a UPnP object"
attempt = 0
while True:
try:
server = UPnPClientServer(("", 1900+attempt), UPnPProtocol)
i = socket.inet_aton(getLocalIPAddress())
server.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
#mcast = reactor.listenMulticast(1900+attempt, self)
break
except socket.error:
attempt = random.randint(0,500)
log.msg("couldn't listen on UPnP port, trying %d"%(
attempt+1900), system='UPnP')
if attempt != 0:
log.msg("warning: couldn't listen on std upnp port", system='UPnP')
#mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)
grpaddr = struct.unpack("I", socket.inet_aton(UPNP_MCAST))[0]
mreq = struct.pack('II', socket.htonl(grpaddr), socket.htonl(socket.INADDR_ANY))
try:
server.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
except socket.error:
dsunittest.traceException("Failed doing IP_ADD_MEMBERSHIP for mreq %r" % mreq)
# apparently on win32, even though this call fails, UPnP works just fine
# so I'm commenting out this raise statement --eries
# raise NoUPnPFound()
return server.discoverUPnP()
示例15: handle_two_side_traffic
def handle_two_side_traffic(nfqueue_element):
try:
ip_packet = dpkt.ip.IP(nfqueue_element.get_payload())
src = socket.inet_ntoa(ip_packet.src)
dst = socket.inet_ntoa(ip_packet.dst)
sport = ip_packet.udp.sport
dport = ip_packet.udp.dport
print(src, sport, dst, dport)
ct = nfct.nfct_new()
if not ct:
raise Exception("nfct_new failed!")
nfct.nfct_set_attr_u8(ct, ATTR_L3PROTO, socket.AF_INET)
nfct.nfct_set_attr_u32(ct, ATTR_IPV4_SRC, socket.htonl(struct.unpack('!I', ip_packet.src)[0]))
nfct.nfct_set_attr_u32(ct, ATTR_IPV4_DST, socket.htonl(struct.unpack('!I', ip_packet.dst)[0]))
nfct.nfct_set_attr_u8(ct, ATTR_L4PROTO, socket.IPPROTO_UDP)
nfct.nfct_set_attr_u16(ct, ATTR_PORT_SRC, socket.htons(sport))
nfct.nfct_set_attr_u16(ct, ATTR_PORT_DST, socket.htons(dport))
nfct.nfct_setobjopt(ct, NFCT_SOPT_SETUP_REPLY)
nfct.nfct_set_attr_u32(ct, ATTR_DNAT_IPV4, socket.htonl(struct.unpack('!I', socket.inet_aton('8.8.8.8'))[0]))
nfct.nfct_set_attr_u16(ct, ATTR_DNAT_PORT, socket.htons(53))
nfct.nfct_set_attr_u32(ct, ATTR_TIMEOUT, 120)
h = nfct.nfct_open(CONNTRACK, 0)
if not h:
raise Exception("nfct_open failed!")
try:
ret = nfct.nfct_query(h, NFCT_Q_CREATE, ct)
if ret == -1:
raise Exception("nfct_query failed!")
finally:
nfct.nfct_close(h)
raw_socket.sendto(str(ip_packet), (dst, 0))
nfqueue_element.drop()
except:
traceback.print_exc()
nfqueue_element.accept()