Implementing the IPv6 server

We will start with the server implementation in a script called echo_server_ipv6.py. The first lines will be the libraries that we will use, which are socket (network and connection utilities) and subprocess (which will allow us to execute commands on the server):

import socket
import subprocess

Then, we will create the variables: ip, port, max_connections, and server. The ip variable will have the string ::1 value, which will be the IPv6 address of the localhost server; the port through which it will accept connections will be passed as an argument to the script; and max_connections will have a numerical value of 5, which indicates the maximum number of simultaneous connections. Finally, with the socket method, we tell Python to wait for connection with the following parameters:

  • socket.AF_INET6: Indicates that we are using the IPv6 protocol
  • socket.SOCK_STREAM: Indicates the type of socket that we are creating, which uses the TCP protocol as a basis and ensures that messages that are sent to the destination arrive in the same order in which they were sent

For example: server_socket = socket.socket(socket.AF_INET6,socket.SOCK_STREAM).

Assign to server.bind the values of IP and port, and to server.listen the number of maximum connections, shown as follows:

dataConection = (host,port)
server_socket.bind(dataConection)
# We assign the maximum number of connections
server_socket.listen(maxConnections)

Finally, we use the server_socket.accept() method to wait for connections from the client:

print("Waiting connections in %s:%s" %(host, port))
connection, address = server_socket.accept()
print ('Connected to', address)

If any data that's received from the client is a command, the logic could be executing that command with the subprocess package and run method. You can find the full documentation about the subprocess module at https://docs.python.org/3.7/library/subprocess.html. For this example, we need the command to execute in a string and the stdout parameter to save the command output in the response variable:

if "command" in data.decode():
s,command = data.decode().split("/")
print("Command:"+command)
response = subprocess.run([command], stdout=subprocess.PIPE)
print(response.stdout)
connection.send(response.stdout)
print ("Sent data command back to the client: [%s]" %response.stdout.decode())

You can find the full server implementation that's given in the following code in the echo_server_ipv6.py file:

#!/usr/bin/env python3

import argparse
import socket
import subprocess

IPV6_ADDRESS = '::1'
# Up to 5 clients can connect
maxConnections = 5

def echo_server_ipv6(port, host=IPV6_ADDRESS):
# Creating the server with ipv6 support
# socket.AF_INET6 to indicate that we will use Ipv6
# socket.SOCK_STREAM to use TCP/IP
try:
server_socket = socket.socket(socket.AF_INET6,socket.SOCK_STREAM)
dataConection = (host,port)
server_socket.bind(dataConection)

# We assign the maximum number of connections
server_socket.listen(maxConnections)
except socket.error as err:
print ("Socket error: %s" %err)
server_socket.close()

print("Waiting connections in %s:%s" %(host, port))
connection, address = server_socket.accept()
print ('Connected to', address)

If we continue analyzing the code, we can see how our infinite loop is listening for client connections. For each message it receives, it will transform it into a command for execution with the subprocess module:

    while True:
data = connection.recv(4096)
print ("Received data from the client: [%s]" %data.decode())
if "command" in data.decode():
s,command = data.decode().split("/")
print("Command:"+command)
response = subprocess.run([command], stdout=subprocess.PIPE)
print(response.stdout)
connection.send(response.stdout)
print ("Sent data command back to the client: [%s]" %response.stdout.decode())
if data.decode() == "exit":
connection.send(bytes("exit".encode('utf-8')))
break
if "command" not in data.decode():
connection.send(data)
print ("Sent data echoed back to the client: [%s]" %data.decode())

print("------- CLOSE CONNECTION ---------")
connection.close()

if __name__ == '__main__':
parser = argparse.ArgumentParser(description='IPv6 Socket Server')
parser.add_argument('--port', action="store", dest="port", type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
echo_server_ipv6(port)

After implementing the server, we started to implement our client, which will send the messages to the socket that was opened by the server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset