===========================
linux-nc-and-python-sockets
===========================


.. role:: raw-latex(raw)
   :format: latex
..

linux-nc-and-python-sockets
===========================

.. _linux-nc-and-python-sockets-1:

linux-nc-and-python-sockets
===========================

nc or netcat lets you create socket servers or connect to services via
sockets.

The nc man page is excellent. This first thing I tried was creating a
simple-chat like program between two terminals.

Simple nc chat application
==========================

Start listening (nc -l) for a connection on a port (31337).

**On terminal A**

.. code-block:: bash

nc -l 31337

Connect to (127.0.0.1) on a port (31337).

**On terminal B**

.. code-block:: bash

nc 127.0.0.1 31337

Like the man page suggests all text submitted on either terminal A or B
will appear on both terminals. Conventionally the server “listening” for
connections is typically labeled the server. In this case neither
terminal is a server because if either closes, both close…

Use python to interact with nc
==============================

On terminal A

.. code-block:: bash

nc -l 31337

On terminal b

.. code-block:: python

python

         import socket s = socket.socket( socket.AF_INET,
         socket.SOCK_STREAM ) s.connect( ( ‘localhost’, 31337 ) )
         s.send( ‘python says hello nc’ ) 20 s.recv( 30 ) ‘nc says hello
         python:raw-latex:`\n`’ # To learn more about sockets do: help(
         s ) # when you are finished run s.close()

The constant socket.AF_INET creates a socket which allows us to connect
to an ip/name and port. The constant socket.AF_UNIX creates a socket
which allows us to connect via files? socket.SOCK_STREAM is the type of
socket (tcp/ip). socket.SOCK_DGRAM (data-gram or UDP)
