本文整理汇总了Python中socket.htons函数的典型用法代码示例。如果您正苦于以下问题:Python htons函数的具体用法?Python htons怎么用?Python htons使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了htons函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_packet
def get_packet():
host = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((host, 0))
# 设置Socket
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# net_data["unknow"] = 0
while True:
buffer = s.recvfrom(65565) # 从Socket中获取数据,不过包含自己信息
port = _struct.unpack('HH', buffer[0][20:24])
# 从Buffer数据中获取网络IP和端口信息
src_ip = "%d.%d.%d.%d" % _struct.unpack('BBBB', buffer[0][12:16])
dest_ip = "%d.%d.%d.%d" % _struct.unpack('BBBB', buffer[0][16:20])
src_port = socket.htons(port[0])
dest_port = socket.htons(port[1])
data_len = len(buffer[0])
key = "%s:%d-%s:%d" % (src_ip, src_port, dest_ip, dest_port)
net_data['process_speed'] = 0
net_data['total_speed'] = 0
if key in process_connections:
net_data['process_speed'] += data_len
net_data['total_speed'] += data_len
示例2: read_reg
def read_reg(self, reg ):
regVal = int(reg)
if (regVal < 0) or (regVal > self.MAX_REG_NUM):
print "Error read_reg: Invalid register number"
return None
#set up listening socket, do before sending read request
sock_readresp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet, UDP
sock_readresp.bind(('', self.UDP_PORT_RREGRESP ))
sock_readresp.settimeout(2)
#crazy packet structure require for UDP interface
READ_MESSAGE = struct.pack('HHHHHHHHH',socket.htons(self.KEY1), socket.htons(self.KEY2),socket.htons(regVal),0,0,socket.htons(self.FOOTER),0,0,0)
sock_read = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet, UDP
sock_read.setblocking(0)
sock_read.sendto(READ_MESSAGE,(self.UDP_IP,self.UDP_PORT_RREG))
sock_read.close()
#try to receive response packet from board, store in hex
data = []
try:
data = sock_readresp.recv(4096)
except socket.timeout:
print "Error read_reg: No read packet received from board, quitting"
sock_readresp.close()
return -1
dataHex = data.encode('hex')
sock_readresp.close()
#extract register value from response
if int(dataHex[0:4],16) != regVal :
print "Error read_reg: Invalid response packet"
return None
dataHexVal = int(dataHex[4:12],16)
return dataHexVal
示例3: get_packet
def get_packet():
HOST = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
net_data["unknow"] = 0
while True:
buf = s.recvfrom(65565)
port = struct.unpack('HH', buf[0][20:24])
src_ip = "%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][12:16])
dest_ip ="%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][16:20])
src_port = socket.htons(port[0])
dest_port = socket.htons(port[1])
data_len = len(buf[0])
key="%s:%d %s:%d"%(src_ip,src_port,dest_ip,dest_port)
if not d_net_info.has_key(key):
get_net_info()
if d_net_info.has_key(key):
key2 ="%s %s"%(key,d_net_info[key])
if net_data.has_key(key2):
net_data[key2] =net_data[key2]+data_len
else:
net_data[key2] = data_len
else:
net_data["unknow"] =net_data["unknow"] + data_len
示例4: get_packet
def get_packet():
HOST = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
HOST = '127.0.0.1' # '169.254.110.192' #'14.23.184.237'
s.bind((HOST, 0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
while True:
buf = s.recvfrom(65565)[0]
# print 'buf[0]'+str(len(buf[0]))+": "+ str(binascii.b2a_hex(buf[0]))
# print 'buf[0]'+str(len(buf)-40)+": "+ str(buf[40:])
port = struct.unpack('HH', buf[20:24])
src_ip = "%d.%d.%d.%d" % struct.unpack('BBBB', buf[12:16])
dest_ip = "%d.%d.%d.%d" % struct.unpack('BBBB', buf[16:20])
src_port = socket.htons(port[0])
dest_port = socket.htons(port[1])
if src_port != 12021 and dest_port != 12021: # or (ord(buf[33]) & 0b00001000 == 0):
continue
data_len = len(buf)
key = "%s:%d - %s:%d - %d - %s" % (src_ip, src_port, dest_ip, dest_port, data_len - 40, str(buf[40:]))
# print key
processData(buf[40:])
示例5: build_message
def build_message(pid, timeout):
"""
Build a datagram packet to send to the condor_master.
The package format is (command, pid, timeout). The command is
always DC_CHILDALIVE (the integer 60008). The pid is the pid of
the process the master is monitoring, i.e. getpid if this
script. The timeout is the amount of time, in seconds, the master
will wait before killing the pid. Each field in the packet must be
8 bytes long, thus the padding.
"""
DC_CHILDALIVE = 60008
message = array.array('H')
message.append(0)
message.append(0)
message.append(0) # padding
message.append(socket.htons(DC_CHILDALIVE))
message.append(0)
message.append(0)
message.append(0) # padding
message.append(socket.htons(pid))
message.append(0)
message.append(0)
message.append(0) # padding
message.append(socket.htons(timeout))
return(message.tostring())
示例6: createPackage
def createPackage(self):
aboname=self.aboName+ '\0';
type = (socket.htons(self.type))
leng = (socket.htons(len(aboname)))
fmt = 'hh%ss%ss'%(len(aboname),len(self.data))
output = struct.pack(fmt,int(type),int(leng),aboname,self.data)
return output
示例7: 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()
示例8: sendOnePing
def sendOnePing(icmpSocket, destAddr, ID, pingnum):
srcChecksum = 0
# Make a dummy header with a 0 checksum.
# bbHHh = signed char, signed char, unsigned short, unsigned short, short
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, srcChecksum, ID, 1)
# d = double
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
srcChecksum = checksum(header + data)
# Calculate the checksum for the packet
if sys.platform == 'darwin': # Mac OS X
#Convert 16-bit integers from host to network byte order.
srcChecksum = socket.htons(srcChecksum) & 0xffff
else: # Linux, UNIX, Windows
srcChecksum = socket.htons(srcChecksum)
# Fill in header checksum with correct value
# bbHHh = signed char, signed char, unsigned short, unsigned short, short
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, srcChecksum, ID, 1)
packet = header + data
if (pingnum == 0):
packetSize = len(packet)
headerSize = len(header)
dataSize = len(data)
print "Pinging " + destAddr + " with " + str(packetSize) + " bytes of data (Header=" + str(headerSize) + " bytes, Data=" + str(dataSize) + " bytes)"
print ""
icmpSocket.sendto(packet, (destAddr, 1))
示例9: sendOnePing
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
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.
myChecksum = 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.
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0,
myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # Don't know about the 1
示例10: sendOnePing
def sendOnePing(mySocket, destAddr, ID):
# Make a dummy header with a 0 checksum
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
header = struct.pack("bbHHh",
ICMP_ECHO_REQUEST, # type (byte)
0, # code (byte)
0, # checksum (halfword, 2 bytes)
ID, # ID (halfword)
1) # sequence (halfword)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
# htons: Convert 16-bit integers from host to network byte order
myChecksum = socket.htons(myChecksum) & 0xffff
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
# AF_INET address must be tuple, not str
mySocket.sendto(packet, (destAddr, 1))
示例11: __make_ack
def __make_ack(seq_num):
"""Make ACK [seq_num].
Input argument: sequence number
Return -> assembled ACK packet
"""
global TYPE_ACK, MSG_FORMAT
# print("making ACK " + str(seq_num))
# Header
# {
# __Type (1 byte)
# __Seq num (1 byte)
# __Checksum (2 bytes)
# __Payload len (2 bytes)
# __Payload
# }
# Make initial message
msg_format = struct.Struct(MSG_FORMAT)
checksum = 0 # First set checksum to 0
init_msg = msg_format.pack(TYPE_ACK, seq_num, checksum, socket.htons(0)) + b''
# Calculate checksum
checksum = __int_chksum(bytearray(init_msg))
# print("checksum = ", checksum)
# A complete msg with checksum
return msg_format.pack(TYPE_ACK, seq_num, checksum, socket.htons(0)) + b''
示例12: __make_data
def __make_data(seq_num, data):
"""Make DATA [seq_num].
Input arguments: sequence number, data, checksum
Return -> assembled packet
"""
global TYPE_DATA, MSG_FORMAT
# print("__make_data() for data = " + data)
# Header
# {
# __Type (1 byte)
# __Seq num (1 byte)
# __Checksum (2 bytes)
# __Payload len (2 bytes)
# }
# Make initial message
msg_format = struct.Struct(MSG_FORMAT)
checksum = 0 # First set checksum to 0
init_msg = msg_format.pack(TYPE_DATA, seq_num, checksum, socket.htons(len(data))) + data
# Calculate checksum
checksum = __int_chksum(bytearray(init_msg))
# print("checksum = " + str(checksum))
# A complete msg with checksum
complete_msg = msg_format.pack(TYPE_DATA, seq_num, checksum, socket.htons(len(data))) + data
# print("__make_data() finished --> " + str(__unpack_helper(complete_msg)))
return complete_msg
示例13: makestruct
def makestruct(self):
#attrs = [i[0] for i in OF_STRUCT]
self.raw = []
for i in xrange(len(OF_STRUCT)):
if i < 1:
self.raw.append(htons(getattr(self, OF_STRUCT[i][0], 0)))
elif 0 < i < 3:
for x in getattr(self, OF_STRUCT[i][0], [0 for i in xrange(6)]):
self.raw.append(x)
else:
#self.raw[i+10] = getattr(self, attrs[i], 0)
if (OF_STRUCT[i][1] == "H"):
self.raw.append(htons(getattr(self, OF_STRUCT[i][0], 0)))
elif (OF_STRUCT[i][1] == "I"):
# Wow, this is ugly. Looking for a better way to do what I want which
# is get a plain int from the formatted address
self.raw.append(int(struct.unpack("I",
inet_aton(getattr(self, OF_STRUCT[i][0], "0.0.0.0")))[0]))
else:
# Bytes don't need htons
self.raw.append(getattr(self, OF_STRUCT[i][0], 0))
# Append the padding
for i in xrange(len(OF_STRUCT[-1][1])-1):
self.raw.append(0)
self.packed = self._struct.pack(*self.raw)
示例14: pf_query_nat
def pf_query_nat(family, proto, src_ip, src_port, dst_ip, dst_port):
[proto, family, src_port, dst_port] = [
int(v) for v in [proto, family, src_port, dst_port]]
packed_src_ip = socket.inet_pton(family, src_ip)
packed_dst_ip = socket.inet_pton(family, dst_ip)
assert len(packed_src_ip) == len(packed_dst_ip)
length = len(packed_src_ip)
pnl = osdefs.pfioc_natlook()
pnl.proto = proto
pnl.direction = osdefs.PF_OUT
pnl.af = family
memmove(addressof(pnl.saddr), packed_src_ip, length)
memmove(addressof(pnl.daddr), packed_dst_ip, length)
pnl.sxport.port = socket.htons(src_port)
pnl.dxport.port = socket.htons(dst_port)
ioctl(pf_get_dev(), osdefs.DIOCNATLOOK,
(c_char * sizeof(pnl)).from_address(addressof(pnl)))
ip = socket.inet_ntop(
pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw)
port = socket.ntohs(pnl.rdxport.port)
return (ip, port)
示例15: makeTcpHeader
def makeTcpHeader(sport, dport, icheckSum=None, char=None):
sourcePort = sport
destAddrPort = dport ### just set to http server
seqNum = 0
ackNum = 0
dataOffset = 5
flagFin = 0
flagSyn = 1
flagRst = 0
flagPsh = 0
flagAck = 0
flagUrg = 0
if char is None:
window = socket.htons(5840) # maximum allowed window size
else:
print (char)
window = socket.htons(ord(char))
if(icheckSum is None):
checkSum = 0
else:
checkSum = icheckSum
urgentPointer = 0
dataOffsetResv = (dataOffset << 4) + 0
flags = (flagUrg << 5) + (flagAck << 4) + (flagPsh << 3) + (flagRst << 2) + (flagSyn << 1) + flagFin
return pack('!HHLLBBHHH', int(sourcePort), int(destAddrPort),
seqNum, ackNum, dataOffsetResv, flags, window,
checkSum, urgentPointer)