async def main(addr): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(addr) while True: data, addr = await sock.recvfrom(10000) print('Received from', addr, data) await sock.sendto(data, addr)
async def try_connect(sockargs, addr, errors): sock = socket.socket(*sockargs) try: await sock.connect(addr) return sock except Exception as e: await sock.close() errors.append(e)
def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.http_conn = h11.Connection(our_role=h11.CLIENT) self.ws_shaker = Handshake('CLIENT') self.ws_conn = ws.Connection('CLIENT', max_buffer=126) self.buffer = ws.TypeFrameBuffer()
def __init__(self, address, port, handler, backlog=100): self.address = address self.port = port self.handler = handler self.backlog = backlog self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.handlers = []
async def main(addr): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) await sock.connect(addr) for i in range(1000): msg = ('Message %d' % i).encode('ascii') print(msg) await sock.send(msg) resp = await sock.recv(1000) assert msg == resp await sock.close()
def create_listening_socket(address): """ Create and return a listening TLS socket on a given address. """ sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(address) sock.listen() return sock
async def sendfrom(data, from_addr): if from_addr not in self.bind_socks: sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sender.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sender.setsockopt(socket.SOL_IP, IP_TRANSPARENT, 1) sender.bind(from_addr) self.bind_socks[from_addr] = sender sender = self.bind_socks[from_addr] await sender.sendto(data, addr)
async def termbin(lines): async with socket.socket() as sock: await sock.connect(('termbin.com', 9999)) for line in lines: assert not line.endswith('\n') await sock.send(line.encode('utf-8') + b'\n') url = (await sock.recv(1024)).decode('ascii').strip() if url == 'Use netcat.': return "Sorry, termbin hates me today :(" return url
async def _make_ssdp_request() -> Tuple[str, str]: """Broadcast a UDP SSDP M-SEARCH packet and return IGD location. Returns: URL to IGD info and IGD IP address. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) await sock.sendto(SSDP_REQUEST, ('239.255.255.250', 1900)) # TODO: add timeout resp, addr = await sock.recvfrom(4096) return _parse_location_from(resp.decode('ascii')), addr[0]
async def async_download(addrs): try: sock = curio_socket.socket() # curio.timeout_after(sock.connect, addr) await sock.connect(addr) await sock.send(VERSION) msg_bytes = await async_read_msg_bytes(sock) await sock.close() return msg_bytes except Exception as e: return None
async def spammer(address, port): async with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while True: try: await sock.sendto(b'lol' * 512, (address, port)) await curio.sleep(0) except curio.TaskCancelled: break await sock.close()
async def connect_async(addr): try: sock = curio_socket.socket() # curio.timeout_after(sock.connect, addr) await sock.connect(addr) await sock.send(VERSION) pkt = await Packet.async_from_socket(sock) msg = VersionMessage.from_bytes(pkt.payload) await sock.close() return msg except Exception as e: print(e) return None
def test_send_package(self): send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) recv_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) recv_socket.bind(("localhost", 0)) connection = Connection(recv_socket.getsockname(), None) assert connection.local_sequence == 0 curio.run(connection._send_next_package, send_socket) data = curio.run(recv_socket.recv, Package._max_size) package = Package.from_datagram(data) assert package.header.sequence == 1 and connection.local_sequence == 1 assert package.header.ack == 0 and package.header.ack_bitfield == "0" * 32 curio.run(connection._send_next_package, send_socket) data = curio.run(recv_socket.recv, Package._max_size) package = Package.from_datagram(data) assert package.header.sequence == 2 and connection.local_sequence == 2 assert package.header.ack == 0 and package.header.ack_bitfield == "0" * 32 connection.local_sequence = Sqn.get_max_sequence() curio.run(connection._send_next_package, send_socket) data = curio.run(recv_socket.recv, Package._max_size) package = Package.from_datagram(data) assert package.header.sequence == 1 and connection.local_sequence == 1 assert package.header.ack == 0 and package.header.ack_bitfield == "0" * 32 curio.run(send_socket.close) curio.run(recv_socket.close)
def find_next_tcp_port(host='0.0.0.0', starting_port=ca.EPICS_CA2_PORT + 1): import socket port = starting_port attempts = 0 while attempts < 100: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) except IOError as ex: port = random.randint(49152, 65535) attempts += 1 else: break return port
async def cmd_associate(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.bind(('', 0)) host, port = sock.getsockname() async with sock: await self._stream.write(self._make_resp(host=host, port=port)) task = await spawn(self.relay_udp(sock)) while True: data = await self._stream.read() if not data: await task.cancel() return if verbose > 0: print('receive unexpect data:', data) except: sock._socket.close()
async def main(): ap = argparse.ArgumentParser() ap.add_argument("--bind", default="127.0.0.1") ap.add_argument("--port", type=int, default=7373) ap.add_argument("--period", type=float, default=3) ap.add_argument("--timeout", type=float, default=7) ap.add_argument("--logconf", default=None) ap.add_argument("--verbose", "--debug", "-v", action='store_true') ap.add_argument("id", type=int) ap.add_argument("callsign", type=str) args = ap.parse_args() if args.id < 0 or args.id > 7: raise ValueError("Invalid ID (must be 0-7)") if len(args.callsign.encode()) > 12: raise ValueError("Callsign too long (max 16 bytes UTF-8)") if args.period < 0.1: raise ValueError( "Heartbeat period too short, refusing to saturate the ether") if args.logconf: logging.config.fileConfig(args.logconf, disable_existing_loggers=False) else: formatter = logging.Formatter( "[{name}] {asctime} {levelname}: {message}", "%Y-%m-%dT%H:%M", '{') stderr_handler = logging.StreamHandler(sys.stderr) stderr_handler.setFormatter(formatter) logging.getLogger().setLevel( logging.DEBUG if args.verbose else logging.INFO) logging.getLogger().addHandler(stderr_handler) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind((args.bind, args.port)) global logger logger = logging.getLogger("heartbeat") timestamps = {} async with curio.TaskGroup() as tg: await tg.spawn( beat(sock, args.port, args.period, args.id, args.callsign, timestamps, args.timeout)) await tg.spawn(listen(sock, timestamps))
async def network(address, peers): async def send(message): await sock.sendto(message.encode(), (host, port)) for peer_addr in resolved_peers: await sock.sendto(message.encode(), peer_addr) async def recv(): return (await sock.recv(2048)).decode() host, port = address ip = await gethostbyname(host) resolved_peers = [(await gethostbyname(peer_host), peer_port) for peer_host, peer_port in peers] async with socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) as sock: sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.bind((ip, port)) yield send, recv
def create_listening_ssl_socket(address, certfile, keyfile): """ Create and return a listening TLS socket on a given address. """ ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.options |= ( ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION ) ssl_context.set_ciphers("ECDHE+AESGCM") ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile) ssl_context.set_alpn_protocols(["h2"]) sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock = ssl_context.wrap_socket(sock) sock.bind(address) sock.listen() return sock
async def udp_server(host, port, handler_task, *, family=socket.AF_INET, reuse_address=True): sock = socket.socket(family, socket.SOCK_DGRAM) try: sock.bind((host, port)) if reuse_address: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) async with sock: while True: data, addr = await sock.recvfrom(8192) try: await handler_task(data, addr) except Exception as e: if verbose > 0: print(e) if verbose > 1: traceback.print_exc() except Exception: sock._socket.close() raise
def create_listening_ssl_socket(address, certfile, keyfile): """ Create and return a listening TLS socket on a given address. """ # check if 2 files exist. If not, raise exceptions if os.path.isfile(certfile) and os.path.isfile(keyfile): ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.options |= (ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION) ssl_context.set_ciphers("ECDHE+AESGCM") ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile) ssl_context.set_alpn_protocols(["h2"]) sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock = ssl_context.wrap_socket(sock) sock.bind(address) sock.listen() return sock else: raise FileNotFoundError( certfile + " and/or " + keyfile + " don't exist. HTTP/2 needs certificate files.")
def __init__(self, cipher_cls, password): self.cipher_cls = cipher_cls self.password = password self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)