我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.htons()。
def __init__(self, ifname, user_id=None, user_pw=None, interactive=False): self.state = 0 self.user_id = user_id self.user_pw = user_pw self.interactive = interactive self.assoc_hwaddr = None self.ifname = ifname self.sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_PAE)) self.sock.bind((ifname, 0)) self.ifindex = get_ifindex(self.sock, self.ifname) self.hwaddr = get_hwaddr(self.sock, self.ifname) SOL_PACKET = 263 PACKET_ADD_MEMBERSHIP = 1 self.sock.setsockopt(SOL_PACKET, PACKET_ADD_MEMBERSHIP, build_mreq(self.ifindex))
def __init__(self, srcp, dstp): self.srcp = srcp self.dstp = dstp self.seqn = 10 self.ackn = 0 self.offset = 5 # Data offset: 5x4 = 20 bytes self.reserved = 0 self.urg = 0 self.ack = 0 self.psh = 0 self.rst = 0 self.syn = 1 self.fin = 0 self.window = socket.htons(5840) self.checksum = 0 self.urgp = 0 self.payload = ""
def send_one_ping(my_socket, dest_addr, ID): """ Send one ping to the given >dest_addr<. """ dest_addr = socket.gethostbyname(dest_addr) # Header is type (8), code (8), checksum (16), id (16), sequence (16) my_checksum = 0 # Make a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytesInDouble = struct.calcsize("d") data = (192 - bytesInDouble) * "Q" data = struct.pack("d", default_timer()) + data # Calculate the checksum on the data and the dummy header. my_checksum = 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. header = struct.pack( "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 ) packet = header + data my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def send_ping(self, sock, ID): """ Send ping to the target host """ target_addr = socket.gethostbyname(self.target_host) my_checksum = 0 # Create a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytes_In_double = struct.calcsize("d") data = (192 - bytes_In_double) * "Q" data = struct.pack("d", time.time()) + bytes(data.encode('utf-8')) # Get the checksum on the data and the dummy header. my_checksum = self.do_checksum(header + data) header = struct.pack( "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 ) packet = header + data sock.sendto(packet, (target_addr, 1))
def await_responce(self, iface): global rev r = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) pkt = r.recvfrom(2048) eth = pkt[0][0:14] eth_d = struct.unpack("!6s6s2s", eth) res = binascii.hexlify(eth_d[0]) dst_mac = self.format_mac(res.decode('utf-8')) local_mac = open('/sys/class/net/{}/address'.format(iface)).read().strip('\n') if dst_mac == local_mac: stop_time = datetime.datetime.now() arp_h = pkt[0][14:42] arp_d = struct.unpack("2s2s1s1s2s6s4s6s4s", arp_h) timee = stop_time - start_time rev += 1 return self.format_mac(binascii.hexlify(arp_d[5]).decode('utf-8')), arp_d[6], timee.total_seconds() * 1000
def send_ping(self, sock, ID): """ Send ping to the target host """ target_addr = socket.gethostbyname(self.target_host) my_checksum = 0 # Create a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytes_In_double = struct.calcsize("d") data = (192 - bytes_In_double) * "Q" data = struct.pack("d", time.time()) + data # Get the checksum on the data and the dummy header. my_checksum = self.do_checksum(header + data) header = struct.pack( "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 ) packet = header + data sock.sendto(packet, (target_addr, 1))
def make_header(self, source_ip, destination_ip, data_len, transport_protocol_len, transport_protocol, ttl=64): srcip = inet_aton(source_ip) # Source port dstip = inet_aton(destination_ip) # Destination port ver = 4 # IP protocol version ihl = 5 # Internet Header Length dscp_ecn = 0 # Differentiated Services Code Point and Explicit Congestion Notification tlen = data_len + transport_protocol_len + 20 # Packet length ident = htons(randint(1, 65535)) # Identification flg_frgoff = 0 # Flags and fragmentation offset ptcl = transport_protocol # Protocol chksm = 0 # Checksum ip_header = pack("!" "2B" "3H" "2B" "H" "4s" "4s", (ver << 4) + ihl, dscp_ecn, tlen, ident, flg_frgoff, ttl, ptcl, chksm, srcip, dstip) chksm = self.checksum(ip_header) return pack("!" "2B" "3H" "2B" "H" "4s" "4s", (ver << 4) + ihl, dscp_ecn, tlen, ident, flg_frgoff, ttl, ptcl, chksm, srcip, dstip)
def __init__(self, *args, **kwargs): super(VRRPInterfaceMonitorNetworkDevice, self).__init__(*args, **kwargs) self.__is_active = True config = self.config if config.is_ipv6: family = socket.AF_INET6 ether_type = ether.ETH_TYPE_IPV6 mac_address = vrrp.vrrp_ipv6_src_mac_address(config.vrid) else: family = socket.AF_INET ether_type = ether.ETH_TYPE_IP mac_address = vrrp.vrrp_ipv4_src_mac_address(config.vrid) # socket module doesn't define IPPROTO_VRRP self.ip_socket = socket.socket(family, socket.SOCK_RAW, inet.IPPROTO_VRRP) self.packet_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ether_type)) self.packet_socket.bind((self.interface.device_name, ether_type, socket.PACKET_MULTICAST, arp.ARP_HW_TYPE_ETHERNET, addrconv.mac.text_to_bin(mac_address))) self.ifindex = if_nametoindex(self.interface.device_name)
def __send_icmp_request(self, icmp_socket, dest_addr, packet_id, sequence): # ICMP Header : # ------------------------------------------------------------------- # | type(8) | code(8) | checksum(16) | packet_id(16) | sequence(16) | # ------------------------------------------------------------------- # packet_checksum = 0 header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, packet_checksum, packet_id, sequence) packet_bytes = struct.calcsize('d') data = (128 - packet_bytes) * '0' data = struct.pack('d', time.time()) + data packet_checksum = self.__checksum(header + data) header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, socket.htons(packet_checksum), packet_id, sequence) packet = header + data icmp_socket.sendto(packet, (dest_addr, 1))
def startServer(self, componentType, cid, gus, targetIP, trycount = 1, timeout = 1): """ """ msg = Define.BytesIO() msg.write( struct.pack("=H", MachineInterface_startserver ) ) # command msg.write( struct.pack("=H", struct.calcsize("=iiQhH") ) ) # command length msg.write( struct.pack("=i", self.uid) ) msg.write( struct.pack("=i", componentType) ) msg.write( struct.pack("=Q", cid) ) msg.write( struct.pack("=h", gus) ) msg.write( struct.pack("=H", socket.htons(self.replyPort)) ) # reply port if trycount <= 0: self.send( msg.getvalue(), targetIP ) self.receiveReply() else: self.sendAndReceive( msg.getvalue(), targetIP, trycount, timeout )
def __init__(self, interface_name, on_ip_incoming, on_ip_outgoing): self.interface_name = interface_name self.on_ip_incoming = on_ip_incoming self.on_ip_outgoing = on_ip_outgoing # The raw in (listen) socket is a L2 raw socket that listens # for all packets going through a specific interface. # SOL_SOCKET: SO_LINGER, SO_RCVBUF, SO_SNDBUF, TCP_NODELAY # SO_LINGER ???????????????????TIME_WAIT????? # ????????????????????tcp?? # SO_RCVBUF?SO_SNDBUF ???????????????? # SO_SNDBUF ?? MSS??????? 2MSS # TCP_NODELAY ?? nagle ?? self.sock = socket.socket( socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_IP)) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 ** 30) self.sock.bind((self.interface_name, ETH_P_IP))
def send_ping(self, sock, ID): """ Send ping to the target host """ target_addr = socket.gethostbyname(self.target_host) my_checksum = 0 # Create a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytes_In_double = struct.calcsize("d") data = (192 - bytes_In_double) * "Q" data = struct.pack("d", time.time()) + data # Get the Checksum on the data and the dummy header. my_checksum = self.do_checksum(header + data) header = struct.pack( "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 ) packet = header + data sock.sendto(packet, (target_addr, 1))
def send_one_ping(my_socket, dest_addr, ID): """ Send one ping to the given >dest_addr<. """ dest_addr = socket.gethostbyname(dest_addr) # Header is type (8), code (8), checksum (16), id (16), sequence (16) my_checksum = 0 # Make a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) #? #a1 = struct.unpack("bbHHh",header) #my test 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. my_checksum = 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. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1) packet = header + data my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def __init__(self, *args, **kwargs): super(SocketSniffer, self).__init__(*args, **kwargs) try: self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL)) if self.interface: self.sock.bind((self.interface, ETH_P_ALL)) except Exception as e: abort('Socket could not be created: {}'.format(e))
def parse_CAddress(vds): d = {} d['nVersion'] = vds.read_int32() d['nTime'] = vds.read_uint32() d['nServices'] = vds.read_uint64() d['pchReserved'] = vds.read_bytes(12) d['ip'] = socket.inet_ntoa(vds.read_bytes(4)) d['port'] = socket.htons(vds.read_uint16()) return d
def pack(self): ver_ihl = (self.version << 4) + self.ihl flags_offset = (self.flags << 13) + self.offset ip_header = struct.pack("!BBHHHBBH4s4s", ver_ihl, self.tos, self.tl, self.id, flags_offset, self.ttl, self.protocol, self.checksum, self.source, self.destination) self.checksum = checksum(ip_header) ip_header = struct.pack("!BBHHHBBH4s4s", ver_ihl, self.tos, self.tl, self.id, flags_offset, self.ttl, self.protocol, socket.htons(self.checksum), self.source, self.destination) return ip_header
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) if iface is not None: self.ins.bind((iface, type))
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0): self.type = type self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) _flush_fd(self.ins) if iface: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30) if promisc is None: promisc = conf.promisc self.promisc = promisc if self.promisc: if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] for i in self.iff: set_promisc(self.ins, i)
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0): if iface is None: iface = conf.iface self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) _flush_fd(self.ins) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) self.ins.bind((iface, type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) self.outs = self.ins self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30) sa_ll = self.outs.getsockname() if sa_ll[3] in conf.l2types: self.LL = conf.l2types[sa_ll[3]] elif sa_ll[1] in conf.l3types: self.LL = conf.l3types[sa_ll[1]] else: self.LL = conf.default_l2 warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name))
def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None, nofilter=0): self.type = type self.outs = None self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) _flush_fd(self.ins) if iface is not None: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) if promisc is None: promisc = conf.sniff_promisc self.promisc = promisc if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] if self.promisc: for i in self.iff: set_promisc(self.ins, i) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
def __init__(self, type = ETH_P_IPV6, filter=None, iface=None, promisc=None, nofilter=0): L3RawSocket.__init__(self, type, filter, iface, promisc) # NOTE: if fragmentation is needed, it will be done by the kernel (RFC 2292) self.outs = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_RAW) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
def getPortNumNetworkByteOrder(st_host): """ Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. :param st_host: :return: 80-20480 """ try: st_host = int(st_host) return socket.htons(st_host) except Exception as e: logging.error("[HostByteOrderPortFalse]: %f %s" % (st_host, repr(e)))
def listen(): last_tid = {} rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) while True: packet = rawSocket.recvfrom(2048) ethernet_header = struct.unpack("!6s6s2s", packet[0][0:14]) if ethernet_header[2] != '\x08\00': continue # not ip ip_header = struct.unpack("!1s1s2s2s1s1s1s1s2s4s4s", packet[0][14:34]) if ip_header[7] != '\x11': continue # not udp if len(packet[0][42:]) < 240: continue # not dhcp dhcp_header = struct.unpack("!1s1s1s1s4s2s2s4s4s4s4s6s10s64s128s4s", packet[0][42:282]) for b in buttons.keys(): if b in binascii.hexlify(ethernet_header[1]) and b in binascii.hexlify(dhcp_header[11]): # filter duplicate presses tid = binascii.hexlify(dhcp_header[4]) if b in last_tid and last_tid[b] == tid: continue last_tid[b] = tid buttons[b](":".join([b[i:i+2] for i in range(0, len(b), 2)]))
def send(sock, addr, id, size, seq=1): # Create an echo request icmp_type = 8 icmp_code = 0 icmp_chksum = 0 icmp_id = id icmp_seq = seq header = struct.pack("bbHHh", icmp_type, icmp_code, icmp_chksum, icmp_id, icmp_seq) # The size of the packet must be large enough to accomodate the header and # a timestamp if size < struct.calcsize("bbHHhd"): raise PacketSizeError() # Create a chunk of data that is prepended by a timestamp so that we can # determine how long it takes the packet to return. timestamp = struct.pack("d", time.time()) data = timestamp + os.urandom(size - struct.caclsize("bbHHhd")) # Now we can figure out the checksum icmp_chksum = socket.htons(checksum(header + data)) # Construct the message using the checksum header = struct.pack("bbHHh", icmp_type, icmp_code, icmp_chksum, icmp_id, icmp_seq) packet = header + data # Send the request to the address host = socket.gethostbyname(addr) sock.sendto(packet, (host, 1))
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
def _setup(self,dev): try: self._s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) self._s.bind((dev,0x0003)) except socket.error as e: raise RuntimeError(e)
def __init__(self, GW_IP, GW_MAC): threading.Thread.__init__(self) self.GW_IP = GW_IP self.GW_MAC = GW_MAC self.arpsock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0806)) # self.arpsock.settimeout(0.1) try: self.arpdata = self.arpsock.recv(65535) except socket.timeout: pass
def convert_integer(): data = 1234 # 32-bit print ("Original: %s => Long host byte order: %s, Network byte order: %s" %(data, socket.ntohl(data), socket.htonl(data))) # 16-bit print ("Original: %s => Short host byte order: %s, Network byte order: %s" %(data, socket.ntohs(data), socket.htons(data)))
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0): self.type = type self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) if iface: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) _flush_fd(self.ins) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30) if promisc is None: promisc = conf.promisc self.promisc = promisc if self.promisc: if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] for i in self.iff: set_promisc(self.ins, i)
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0): if iface is None: iface = conf.iface self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) self.ins.bind((iface, type)) _flush_fd(self.ins) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) self.outs = self.ins self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30) sa_ll = self.outs.getsockname() if sa_ll[3] in conf.l2types: self.LL = conf.l2types[sa_ll[3]] elif sa_ll[1] in conf.l3types: self.LL = conf.l3types[sa_ll[1]] else: self.LL = conf.default_l2 warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name))
def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None, nofilter=0): self.type = type self.outs = None self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) if iface is not None: self.ins.bind((iface, type)) if not nofilter: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if filter is not None: attach_filter(self.ins, filter) if promisc is None: promisc = conf.sniff_promisc self.promisc = promisc if iface is None: self.iff = get_if_list() else: if iface.__class__ is list: self.iff = iface else: self.iff = [iface] if self.promisc: for i in self.iff: set_promisc(self.ins, i) _flush_fd(self.ins) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
def bootstrap(self): if ((self.__IN__ not in self.itemlist) or (self.__OUT__ not in self.itemlist)): return s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) s.bind((self[self.__IN__], 0)) self._in = s s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) r = s.bind((self[self.__OUT__], 0)) self._out = s
def __calc_udp_csum(saddr, daddr, udp_data, is_ipv6=False): size = len(udp_data) seq = [ saddr, daddr, b'\x00\x11', utils.number2bytes(size, 2), udp_data, ] if is_ipv6: size += 24 else: size += 12 if 0 != size % 2: seq.append(b"\0") size += 1 data = b"".join(seq) csum = socket.htons(fn_utils.calc_csum(data, size)) # csum = __calc_checksum(data, size) # import socket # print(csum,socket.htons(csum_t)) if csum == 0: return 0xffff return csum