Python socket.IP_TTL Examples
The following are 6
code examples of socket.IP_TTL().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example #1
Source File: ping3.py From ping3 with MIT License | 6 votes |
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
Example #2
Source File: traceroute.py From FinalRecon with MIT License | 5 votes |
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
Example #3
Source File: traceroute.py From FinalRecon with MIT License | 5 votes |
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
Example #4
Source File: dnstraceroute.py From dnsdiag with BSD 2-Clause "Simplified" License | 5 votes |
def sendto(self, *args, **kwargs): global _ttl if _ttl: self.setsockopt(socket.SOL_IP, socket.IP_TTL, _ttl) super(CustomSocket, self).sendto(*args, **kwargs)
Example #5
Source File: twampy.py From twampy with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #6
Source File: __init__.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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