当前位置: 首页>>代码示例>>Python>>正文


Python socket.IP_TTL属性代码示例

本文整理汇总了Python中socket.IP_TTL属性的典型用法代码示例。如果您正苦于以下问题:Python socket.IP_TTL属性的具体用法?Python socket.IP_TTL怎么用?Python socket.IP_TTL使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在socket的用法示例。


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

示例1: bind

# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_TTL [as 别名]
def bind(self, addr, port, tos, ttl, df):
        log.debug(
            "bind(addr=%s, port=%d, tos=%d, ttl=%d)", addr, port, tos, ttl)
        self.socket = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, tos)
        self.socket.setsockopt(socket.SOL_IP,     socket.IP_TTL, ttl)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((addr, port))
        if df:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 2)
            elif (sys.platform == "win32"):
                self.socket.setsockopt(socket.SOL_IP, 14, 1)
            elif (sys.platform == "darwin"):
                log.error("do-not-fragment can not be set on darwin")
            else:
                log.error("unsupported OS, ignore do-not-fragment option")
        else:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 0) 
开发者ID:nokia,项目名称:twampy,代码行数:23,代码来源:twampy.py

示例2: udp_send

# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_TTL [as 别名]
def udp_send(ip, port, ttl, rx, status, tr_tout, output, collect):
	tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
	tx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	tx.setblocking(0)
	tx.settimeout(tr_tout)
	tx.sendto(''.encode(), (ip, port))

	try:
		data, curr_addr = rx.recvfrom(512)
		curr_addr = curr_addr[0]
	except socket.error as e:
		curr_addr = '* * *'
	finally:
		tx.close()
	
	hop_index = str(ttl)
	hop_addr = curr_addr
	if hop_addr != '* * *':
		try:
			hop_host = socket.gethostbyaddr(hop_addr)[0]
		except socket.herror:
			hop_host = 'Unknown'
	else:
		hop_addr = '* * *'
		hop_host = ''

	print(G + hop_index.ljust(7) + C + hop_addr.ljust(17) + W + hop_host)
	if output != 'None':
		collect.setdefault('Result', []).append([str(hop_index), str(hop_addr), str(hop_host)])

	if curr_addr == ip:
		status['end'] = True 
开发者ID:thewhiteh4t,项目名称:FinalRecon,代码行数:35,代码来源:traceroute.py

示例3: sendto

# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_TTL [as 别名]
def sendto(self, *args, **kwargs):
        global _ttl
        if _ttl:
            self.setsockopt(socket.SOL_IP, socket.IP_TTL, _ttl)
        super(CustomSocket, self).sendto(*args, **kwargs) 
开发者ID:farrokhi,项目名称:dnsdiag,代码行数:7,代码来源:dnstraceroute.py

示例4: send_echo_request

# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_TTL [as 别名]
def send_echo_request(self, id, addr, ttl, timeout):
      self.sock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

      if not self.files.has_key(id):
        raise Fault(8002, "asked to send ICMP echo request for id not open.")
      
      file = self.files[id]
      type = ICMP_ECHO_REQUEST     
      buf = struct.pack("!BBHHH", ICMP_ECHO_REQUEST, 0x00, 0x0000,
                                  id, file.seqno )  
      sum = self._calc_checksum(buf)    
      buf = struct.pack("!BBHHH", ICMP_ECHO_REQUEST, 0x00, sum,
                                  id, file.seqno )  

      df = Deferred() 
      df.seqno = file.seqno
      file.seqno += 1
      df.id = id
      if not self.dfs.has_key(df.id):
          self.dfs[df.id] = [df]
      else:
          self.dfs[df.id].append(df)  # deferreds for this id.
      df.timestamp = bttime()
      self.sock.sendto(buf, (addr,22))
      reactor.callLater( timeout, self._handle_timeout, df.id, df.seqno )
      return df 
开发者ID:kenorb-contrib,项目名称:BitTorrent,代码行数:28,代码来源:__init__.py

示例5: tcp_send

# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_TTL [as 别名]
def tcp_send(ip, port, ttl, rx, status, tr_tout, output, collect):
	tx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	tx.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl))
	tx.setblocking(0)
	tx.settimeout(tr_tout)
	
	while True:
		try:
			try:
				tx.connect((ip, port))
				hop_index = str(ttl)
				try:
					hop_host = socket.gethostbyaddr(ip)[0]
				except socket.herror:
					hop_host = 'Unknown'
				print(G + hop_index.ljust(7) + C + ip.ljust(17) + W + hop_host)
				status['end'] = True
				if output != 'None':
					collect.setdefault('Result', []).append([str(hop_index), str(ip), str(hop_host)])
			except (socket.error, socket.timeout) as err:
				try:
					data, curr_addr = rx.recvfrom(512)
					curr_addr = curr_addr[0]
				except socket.timeout:
					curr_addr = '* * *'
				hop_index = str(ttl)
				hop_addr = curr_addr
				if hop_addr != '* * *':
					try:
						hop_host = socket.gethostbyaddr(hop_addr)[0]
					except socket.herror:
						hop_host = 'Unknown'
				else:
					hop_addr = '* * *'
					hop_host = ''
				print(G + hop_index.ljust(7) + C + hop_addr.ljust(17) + W + hop_host)
				if output != 'None':
					collect.setdefault('Result', []).append([str(hop_index), str(hop_addr), str(hop_host)])
				continue
		finally:
			tx.close()
			break 
开发者ID:thewhiteh4t,项目名称:FinalRecon,代码行数:44,代码来源:traceroute.py

示例6: ping

# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_TTL [as 别名]
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56, interface: str = None) -> float or None:
    """
    Send one ping to destination address with the given timeout.

    Args:
        dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com"
        timeout: Time to wait for a response, in seconds. Default is 4s, same as Windows CMD. (default 4)
        unit: The unit of returned value. "s" for seconds, "ms" for milliseconds. (default "s")
        src_addr: WINDOWS ONLY. The IP address to ping from. This is for multiple network interfaces. Ex. "192.168.1.20". (default None)
        interface: LINUX ONLY. The gateway network interface to ping from. Ex. "wlan0". (default None)
        ttl: The Time-To-Live of the outgoing packet. Default is 64, same as in Linux and macOS. (default 64)
        seq: ICMP packet sequence, usually increases from 0 in the same process. (default 0)
        size: The ICMP packet payload size in bytes. If the input of this is less than the bytes of a double format (usually 8), the size of ICMP packet payload is 8 bytes to hold a time. The max should be the router_MTU(Usually 1480) - IP_Header(20) - ICMP_Header(8). Default is 56, same as in macOS. (default 56)

    Returns:
        The delay in seconds/milliseconds or None on timeout.

    Raises:
        PingError: Any PingError will raise again if `ping3.EXCEPTIONS` is True.
    """
    with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as sock:
        sock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        if interface:
            sock.setsockopt(socket.SOL_SOCKET, SOCKET_SO_BINDTODEVICE, interface.encode())  # packets will be sent from specified interface.
            _debug("Socket Interface Binded:", interface)
        if src_addr:
            sock.bind((src_addr, 0))  # only packets send to src_addr are received.
            _debug("Socket Source Address Binded:", src_addr)
        thread_id = threading.get_native_id() if hasattr(threading, 'get_native_id') else threading.currentThread().ident  # threading.get_native_id() is supported >= python3.8.
        process_id = os.getpid()  # If ping() run under different process, thread_id may be identical.
        icmp_id = zlib.crc32("{}{}".format(process_id, thread_id).encode()) & 0xffff  # to avoid icmp_id collision.
        try:
            send_one_ping(sock=sock, dest_addr=dest_addr, icmp_id=icmp_id, seq=seq, size=size)
            delay = receive_one_ping(sock=sock, icmp_id=icmp_id, seq=seq, timeout=timeout)  # in seconds
        except errors.HostUnknown as e:  # Unsolved
            _debug(e)
            _raise(e)
            return False
        except errors.PingError as e:
            _debug(e)
            _raise(e)
            return None
        if delay is None:
            return None
        if unit == "ms":
            delay *= 1000  # in milliseconds
    return delay 
开发者ID:kyan001,项目名称:ping3,代码行数:49,代码来源:ping3.py


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