64 lines
1.8 KiB
Python
Executable File
64 lines
1.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
import argparse
|
|
import logging
|
|
import socket
|
|
|
|
LOGGER = logging.getLogger(__name__)
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--address", help="The IPv6 address to bind")
|
|
parser.add_argument("--port", "-p", default=50007, help="The port to connect to.")
|
|
parser.add_argument("--verbose", action="store_true", help="Verbose logging")
|
|
args = parser.parse_args()
|
|
|
|
logging.basicConfig(
|
|
format="%(asctime)s %(message)s",
|
|
level=logging.DEBUG if args.verbose else logging.INFO,
|
|
)
|
|
|
|
hostname = socket.gethostname()
|
|
addresses = []
|
|
for interface in socket.if_nameindex():
|
|
interface_name = interface[1]
|
|
LOGGER.debug("Found interface %s", interface_name)
|
|
try:
|
|
addrs = socket.getaddrinfo(host=hostname, port=80, family=socket.AF_INET6)
|
|
for addr in addrs:
|
|
addresses.append((interface_name, addr[4][0]))
|
|
except socket.gaierror:
|
|
LOGGER.info("Interfare '%s' has no IPv6 addresses", interface_name)
|
|
addresses = [addr for addr in socket.getaddrinfo(host=args.address, port=args.port, family=socket.AF_INET6, type=socket.SOCK_STREAM, proto=0, flags=0)]
|
|
if not addresses:
|
|
raise ValueError("Couldn't find ipv6 address for source %s" % source_ip)
|
|
if len(addresses) > 1:
|
|
raise ValueError("Not sure which address you want")
|
|
address = addresses[0]
|
|
logging.info("Binding %s", address)
|
|
bind_socket(*address)
|
|
|
|
def bind_socket(family, type_, proto, canonname, sockaddr):
|
|
sock = socket.socket(
|
|
family=family,
|
|
type=type_,
|
|
proto=proto,
|
|
)
|
|
sock.bind(sockaddr)
|
|
LOGGER.info("Bound %s", sockaddr)
|
|
try:
|
|
sock.listen(1)
|
|
except OSError as msg:
|
|
sock.close()
|
|
return
|
|
while True:
|
|
conn, addr = sock.accept()
|
|
with conn:
|
|
LOGGER.info("Connected by %s", addr)
|
|
while True:
|
|
data = conn.recv(1024)
|
|
if not data: break
|
|
conn.send(("Hey " + data.decode("UTF-8")).encode("UTF-8"))
|
|
|
|
if __name__ == "__main__":
|
|
main()
|