Linux sockets are available to applications running within the guest shell. Sockets can be used for communication between applications residing within the guest shell, as well as remote applications. An example would be an echo server, written in Python. This will echo back any text that it receives on a socket:
#!/usr/bin/env python
import socket
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
if (data == "done"):
print "received a done message, exiting"
client.send("server done, exiting")
client.close()
s.close()
break
else :
print data
client.send(data)
client.close()
s.close()
The code above will use Python to create a socket stream and listen on port 50000. Any text it receives will be sent back to the sender. If done is entered the server will close its socket and exit.
This can be used with an echo client application, which can reside remotely. A sample echo client may look like the following:
`#!/usr/bin/env python`
import socket
host = '<ip address of echo server>'
port = 50000
size = 1024
while(True):
test = raw_input('Enter Data to send to server: ')
if (test == 'q') or (test == 'quit'):
break
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send(test)
data = s.recv(size)
print 'Received:', data
s.close()
print 'done'
The Python code above will take input from the command line through the raw_input call and send it to the echo server through the socket connection.
Here is a sample run of both the client and server:
Open NX-OS provides guest shell, a native LXC container for switch management and hosting applications. Other LXC containers can be created in Open NX-OS for third-party or custom applications.
Server side (Running inside of Guest Shell using the management VRF):
[guestshell@guestshell gs]$ sudo chvrf management Python echoserver.py
Hello Server
Please echo this text
received a done message, exiting
[guestshell@guestshell gs]$
Client side (Running on an external Linux Server):
./echoclient.py
Enter Data to send to server: Hello Server
Received: Hello Server
Enter Data to send to server: Please echo this text
Received: Please echo this text
Enter Data to send to server: done
Received: server done, exiting
Enter the Data to send to server: quit
done
The server can also accept multiple incoming sockets and below is an example where two clients have connected simultaneously:
[guestshell@guestshell gs]$ sudo chvrf management Python echoserver.py
hello from client 1
hello from client 2