Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.5 kB
3
Indexable
Never
#!/usr/bin/env python3
import socket
import struct
import sys

def send_to_tcp_server(host, port, payload):
    # Ensure payload is of type bytes
    if not isinstance(payload, bytes):
        raise ValueError("Payload must be of type bytes")

    # Size of the payload in bytes
    payload_size = len(payload)

    # Check if payload_size is less than or equal to 65535 (2 bytes)
    if payload_size > 65535:
        raise ValueError("Payload cannot be longer than 65535 bytes")

    # Prepare data to send: 2-byte payload size + payload
    # Use format 'H' (unsigned short) for 2-byte size
    header = struct.pack('!H', payload_size)
    message = header + payload

    try:
        # Create a TCP socket
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            # Connect to the server
            sock.connect((host, port))

            # Send the data
            sock.sendall(message)
            print(f"Data sent successfully to {host}:{port}")
    except socket.error as e:
        print(f"Socket error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Unexpected error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python send_to_tcp.py <host> <port> <payload>")
        sys.exit(1)

    host = sys.argv[1]
    port = int(sys.argv[2])
    payload = sys.argv[3].encode()  # Assume payload is text that needs to be encoded to bytes

    send_to_tcp_server(host, port, payload)
Leave a Comment