本文整理汇总了Python中socket.htons函数的典型用法代码示例。如果您正苦于以下问题:Python htons函数的具体用法?Python htons怎么用?Python htons使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了htons函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:RainSong,项目名称:PythonSample,代码行数:30,代码来源:ProcessNetWorkData.py
示例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
开发者ID:jhugon,项目名称:femb_udp,代码行数:35,代码来源:femb_udp_cmdline.py
示例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
开发者ID:JunfeiYang,项目名称:Python_project,代码行数:29,代码来源:python_check_network.py
示例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:])
开发者ID:keyou,项目名称:NetSniffer,代码行数:25,代码来源:Sniffer.py
示例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())
开发者ID:fpierfed,项目名称:owl,代码行数:29,代码来源:owld.py
示例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
开发者ID:fnal,项目名称:elComandante,代码行数:7,代码来源:sclient.py
示例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()
开发者ID:fqrouter,项目名称:west-chamber,代码行数:35,代码来源:userspace_nat.py
示例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))
开发者ID:GenevaS,项目名称:NetworkingPrograms,代码行数:32,代码来源:icmpPing.py
示例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
开发者ID:vmiklos,项目名称:vmexam,代码行数:25,代码来源:ping.py
示例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))
开发者ID:niezgodny,项目名称:traceroute-python,代码行数:26,代码来源:traceroute.py
示例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''
开发者ID:JRChow,项目名称:RDT-3.0,代码行数:29,代码来源:rdt3.py
示例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
开发者ID:JRChow,项目名称:RDT-3.0,代码行数:30,代码来源:rdt3.py
示例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)
开发者ID:chihiroshindou,项目名称:openflow-netfpga,代码行数:27,代码来源:of_header.py
示例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)
开发者ID:Kriechi,项目名称:sshuttle,代码行数:26,代码来源:pf.py
示例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)
开发者ID:kimhj3715,项目名称:C8505_A1_CovertChannel,代码行数:31,代码来源:covert.py
示例16: src_port
def src_port(self):
if hasattr(self, "sport"):
return socket.htons(self.sport)
elif hasattr(self, "inet_sport"):
return socket.htons(self.inet_sport)
else:
return None
开发者ID:woogers,项目名称:volatility,代码行数:7,代码来源:linux.py
示例17: __init__
def __init__(self, src, dst):
self.src = bytes(bytearray.fromhex(src))
self.dst = bytes(bytearray.fromhex(dst))
self.type = socket.htons(257)
self.socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
self.socket.bind(("eth0", 0))
print(self.socket)
开发者ID:guardhunt,项目名称:TelemeterRC_Receive,代码行数:7,代码来源:TelemeterRC.py
示例18: sendOnePing
def sendOnePing(mySocket, destAddr, ID):
# Make a dummy header with a 0 checksum.
myChecksum = 0
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
# Pack binary data that keeps track of the current time right before we sendOnePing()
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 it in the header
if sys.platform == 'darwin':
#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
# Send the ping to the destination address
# AF_INET address must be tuple, not str
mySocket.sendto(packet, (destAddr, 1))
开发者ID:creamerm,项目名称:NetworkingProject2,代码行数:27,代码来源:ICMPPinger.py
示例19: build_packet
def build_packet():
# In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our
# packet to be sent was made, secondly the checksum was appended to the header and
# then finally the complete packet was sent to the destination.
# Make the header in a similar way to the ping exercise.
# Append checksum to the header.
# Don’t send the packet yet , just return the final packet in this function.
# So the function ending should look like this
# packet = header + data
# return packet
myChecksum = 0
myID = os.getpid() & 0xFFFF
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, myID, 1)
data = struct.pack("d", time.time())
myChecksum = checksum(header + data)
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, myID, 1)
packet = header + data
return packet
开发者ID:aadamsaleem,项目名称:Networking,代码行数:25,代码来源:traceroute.py
示例20: recv_udp
def recv_udp(listener, bufsize):
debug3('Accept UDP using socket_ext recvmsg.\n')
srcip, data, adata, flags = listener.recvmsg(
(bufsize,), socket.CMSG_SPACE(24))
dstip = None
family = None
for a in adata:
if a.cmsg_level == socket.SOL_IP and a.cmsg_type == IP_ORIGDSTADDR:
family, port = struct.unpack('=HH', a.cmsg_data[0:4])
port = socket.htons(port)
if family == socket.AF_INET:
start = 4
length = 4
else:
raise Fatal("Unsupported socket type '%s'" % family)
ip = socket.inet_ntop(
family, a.cmsg_data[start:start + length])
dstip = (ip, port)
break
elif a.cmsg_level == SOL_IPV6 and a.cmsg_type == IPV6_ORIGDSTADDR:
family, port = struct.unpack('=HH', a.cmsg_data[0:4])
port = socket.htons(port)
if family == socket.AF_INET6:
start = 8
length = 16
else:
raise Fatal("Unsupported socket type '%s'" % family)
ip = socket.inet_ntop(
family, a.cmsg_data[start:start + length])
dstip = (ip, port)
break
return (srcip, dstip, data[0])
开发者ID:AdamIsrael,项目名称:sshuttle,代码行数:32,代码来源:client.py
注:本文中的socket.htons函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论