TCP Server Creation in Python

Jul 26, 2024

TCP Server Creation in Python

Introduction

  • Focus on creating a TCP server in Python.
  • Future video will cover creating a client and demonstrating communication between the server and client.
  • Using Windows with Visual Studio Code and Microsoft Python extension.

Understanding Sockets

  • What is a Socket?
    • Technical Definition: An internal endpoint for sending and receiving data.
    • Simple Analogy: Like an outlet that provides a power connection, but for data transmission.
  • Importance of sockets in penetration testing and data communication.

Socket Module in Python

  • Part of the Python standard library.
  • To use the socket module, you need to import it in your script.
  • Syntax to create a socket:
    socket.socket()
    

Socket Parameters

  • Socket Family: Generally specified using socket.AF_INET (for IPv4) or socket.AF_INET6 (for IPv6).
  • Socket Type:
    • socket.SOCK_STREAM for TCP (connection-oriented).
    • socket.SOCK_DGRAM for UDP (connectionless).

Important Socket Methods

  • bind(): Binds the host and port to a socket.
  • listen(): Starts the TCP listener.
  • accept(): Accepts incoming TCP connection requests.
  • send(): Sends a message over TCP.
  • recv(): Receives messages over TCP.
  • close(): Closes the socket connection.

Creating a TCP Server

  1. Set up Environment

    • Save file as server.py in Visual Studio Code.
    • Make sure to run on Python 3.
  2. Import the Socket Module

    import socket
    
  3. Create a Socket Object

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
  4. Get Hostname and Bind

    • Get local hostname:
      host = socket.gethostname()
      
    • Specify port (e.g., 444)
    • Bind socket to host and port:
      server_socket.bind((host, port))
      
  5. Listen for Connections

    server_socket.listen(3)  # maximum 3 connections
    
  6. Accept Connections in a Loop

    while True:
        client_socket, address = server_socket.accept()
        print(f'Connection received from {address}')
        ```
    
    
  7. Send Message to Client

    • Create a message:
      message = 'Thank you for connecting to the server!'
      
    • Send message:
      client_socket.send(message.encode())
      
  8. Close Client Socket

    client_socket.close()
    

Summary

  • Set up a TCP server using the socket module in Python.
  • Create socket with specified family and type (TCP).
  • Bind to host and port, listen for connections, and handle communication.
  • Code will be available on GitHub for further review and testing.

Additional Notes

  • Mistakes may occur; clarification and support can be requested in comments or privately via a website.
  • Expect improvements and documentation to be added on GitHub.