Skip to content

Instantly share code, notes, and snippets.

@Suzhou65
Created May 7, 2024 15:30
Show Gist options
  • Save Suzhou65/48df6a67eca5d7a44b9e99b59b30403c to your computer and use it in GitHub Desktop.
Save Suzhou65/48df6a67eca5d7a44b9e99b59b30403c to your computer and use it in GitHub Desktop.
Some python socket testing

Transmitter

import socket
def LocalBroadcasting(Payload,SelectAddress=(),SelectProtocolNumber=()):
    # Trans
    if len(Payload) == 17:
        SeparateCharacter = Payload[2]
        Payload = Payload.replace(SeparateCharacter,"")
        PacketPayload = bytes.fromhex("F" * 12 + Payload *16)
    elif len(Payload) == 12:
        PacketPayload = bytes.fromhex("F" * 12 + Payload *16)
    # Broadcast socket config
    BroadcastMission = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    BroadcastMission.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1)
    BroadcastMission.sendto(PacketPayload,(SelectAddress,SelectProtocolNumber))
    BroadcastMission.close()

Receiving

import socket
# Runtime
try:
    # Get host info
    HostAddress = "127.0.0.1"
    # Socket configuration
    ListeningSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    HostProtocol = 8080
    ListeningSocket.bind((HostAddress,HostProtocol))
    # Loop
    while True:
        # Listening
        ReceivingData, ReceivingAddress = ListeningSocket.recvfrom(128)
        # Receiving packet
        if ReceivingData is not None:
            print(ReceivingData)
            print(type(ReceivingData))
        # If not, keep listening
        else:
            continue
except PermissionError:
    ErrorMessage = ("Ports below 1024 are privileged, require root privilege.")
    print(f"{ErrorMessage}\r\n")
except:
    pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment