#networks

1 messages ¡ Page 5 of 1

queen axle
#

in my script

#

what protocol has that "messaging" concept?

#

well, in other words, what protocol(s) does irc use?

open isle
open isle
#

But this little system where you send a fixed amount of bytes describing the length of the rest of the response (ie. the payload) is actually a protocol! we just designed our own, those first four bytes of each "message" is the header

queen axle
#

ooo

#

I thought the header was much larger than 4 bytes

open isle
#

well the TCP, IP, and Ethernet headers are much bigger, but we're building our own protocol on top of TCP and the rest of the network stack

#

this is what we do all of the time in networking, HTTP is a protocol that's done over TCP

queen axle
#

I see, I'll try out the method u sent above in a moment

open isle
#
<[header] 4 bytes -> length of payload> <[payload] X bytes>
<[header] 4 bytes -> length of payload> <[payload] X bytes>
<[header] 4 bytes -> length of payload> <[payload] X bytes>

anyway, this is sorta what it looks at the TCP level, the length of the payload is known after reading the first four preceding bytes

open isle
#

IIRC you said something was fragmented? can you determine how many bytes the whole message will be before sending it?

queen axle
#

bytes will be about 1024

#

also what's blob in the last line

open isle
#

the other side will need to know exactly, the sender would look something like this

message = b"some bytes"
message_length = len(message)
s.send(message_length.to_bytes(4, byteorder="big"))
s.send(message)
open isle
queen axle
#

all good

#

hmm but doesn't from_bytes return the first argument as integer

#

also I found a bit_length() method

open isle
#

yup, bytes_sent is the number of bytes sent by the other side, maybe it would've been better to call it message_length 😅

queen axle
#

oh wait hold on

open isle
#
CLIENT                     SERVER (wants to send b'hello')
                             - encodes the integer 5 into 4 bytes 
                             - send() b'\x00\x00\x00\x05'
                             - send() b'hello'

- recv() 4 bytes exactly
- converts those bytes into
  an integer (5)
- recv() in a loop until
  5 bytes have been received
- once 5 bytes have been
  received, the client knows
  it's done reading and
  stops the loop

does this help explain what's happening?

queen axle
#

yeah

open isle
#

there's no simple way of showing 5 encoded in bytes, hence the generic hexadecimal bytes representation: b'\x00\x00\x00\x05'

#

b"5" is not the same thing as the integer 5 encoded in bytes

queen axle
#

anyways

#

I just noticed, when the server replies with a long message, the message is fragmented, the recv() function seems to hold all fragments because I printed the received data, it printed the first fragment, then it seems like the function put itself on hold until user types some input, then the second fragment is printed

open isle
#

yeah, the protocols down the stack (IP layer or the Ethernet layer) might be fragmenting the data as it's being sent over the wire, recv(some_number) only guarantees that it'll return UP TO #some_number bytes

#

that's why we still have to loop after determining the length, we might need several recv calls to get the full messages/payload

#

the length header tells us when to stop looping

queen axle
#

hmm ok, bytes_sent = int.from_bytes(s.recv(4), byteorder="big") I'm confused how this returns the length of the payload

open isle
#

FWIW, you're welcome to find some networking library that implements some message based protocol for you, but I find implementing my own simpler (and I don't know any libraries anyway) and a good learning experience

open isle
open isle
queen axle
#

oh that's right

queen axle
#

@open isle seems like it's still hanging

open isle
#

hmm, what's the code of the receiver and sender

queen axle
#

hold on I think I did something wrong

open isle
queen axle
#

oh thanks

open isle
queen axle
#

can't tell, it's just an empty input, pressing enter just creates a new line

#

part of the serverpy conn.sendall(len(child.stdout.read().decode())) # send length of data so client can digest the payload conn.sendall((child.stdout.read().decode()+'\n').encode()) part of the client ```py
def receive_data(sock):
response_len = int(sock.recv(4).decode())
response = bytearray()
while len(response) < response_len:
data = sock.recv(1024)
if not data: break
response.extend(data)
return response

#

I have a feeling the syntax for the server is incorrect or something

open isle
#

hmm

queen axle
#

oh wait, maybe I have to encode the first line in the server

#

durr

open isle
#
conn.sendall(len(child.stdout.read().decode()).to_bytes(4))

?

queen axle
#

hmm I can try that yeah

open isle
#

you should also probably save child.stdout.read().decode() into a separate variable just for readability

queen axle
#

yeah I was about to say

#

still seems to hang

open isle
#

yeah, the first line of receive_data() needs to be response_len = int.from_bytes(sock.recv(4))

queen axle
#

what's the difference between the two?

open isle
#

.decode() converts bytes into a string

#

go away lance

queen axle
#

but then I turn that string into an int

open isle
#

well yeah you can do that, encode the message length in a stringified number, but IMO it's simpler to just encode the integer in raw bytes, skipping unicode

#

but we can do it your way

queen axle
#

actually it makes more sense to do that

open isle
#

which way do you want do encode the length?

queen axle
#

I switched it to from_bytes

open isle
#

raw bytes:

# sender
conn.sendall(len(proc_output).to_bytes(4))
# receiver
response_len = int.from_bytes(sock.recv(4))

unicode based:

# sender
conn.sendall(len(proc_output).zfill(4).encode("utf-8"))
# receiver
response_len = int(sock.recv(4).decode())
#

zfill is necessary to make sure the stringifed number is always four characters (and therefore four bytes) long

#

!e print("5".zfill(4))

errant bayBOT
#

@open isle :white_check_mark: Your 3.11 eval job has completed with return code 0.

0005
queen axle
#

client py def receive_data(sock): response_len = int.from_bytes(sock.recv(4), byteorder="big") response = bytearray() while len(response) < response_len: data = sock.recv(1024) if not data: break response.extend(data) return response server py command_out = child.stdout.read().decode() conn.sendall(command_out.to_bytes(4)) # send length of data so client can digest the payload conn.sendall((command_out + '\n').encode())

open isle
#
conn.sendall(command_out.to_bytes(4))

should be

conn.sendall((len(command_out) + 1).to_bytes(4))

because you're trying to encode an int (which is the length) into bytes, not a string

#

the +1 is necessary because you're sending an extra newline in that second sendall call :)

queen axle
#

appreciate it

#

still hanging tho

open isle
#

huh

#

I'm going to copy and paste your code and run it locally

#

I probably missed something

queen axle
#

here

#

server py command_out = child.stdout.read().decode() conn.sendall((len(command_out)+1).to_bytes(4)) # send length of data so client can digest the payload conn.sendall((command_out + '\n').encode())

#

and client is still the same

#

and I should be returning response because it has all the combined data right?

#

then that can be used with .decode() outside the function

open isle
#

yup, you got it

queen axle
#

anyways, so are headers usually sent before the payload? Or are they usually combined into one datagram?

open isle
#

depends, and that is a good point since it is possible for the header itself to be fragmented which means recv(4) isn't guaranteed to work but that would be a rare failure case

storm saffron
#

with TCP python doesn't let you see the individual datagrams

#

it's all just a stream of bytes

#

or at least the socket library doesn't

#

there's a very good reason for that which I'm sure someone told me

#

so you can't really rely on receiving a 'header packet' then a 'content packet'

queen axle
storm saffron
#

possibly i mean the socket library itself

#

since it's built around providing magic pipes from one end to another

open isle
errant bayBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

queen axle
#

sure here

#

I'm making my own version of a ssh

open isle
#

to be honest, I've always wanted to make my own but I never completed my project. I'm having fun helping you, it's like completing a project I've put away for too long haha

queen axle
#

heh that's cool

#

when I'm done with the project, I'll remake it in C-lang or C++

open isle
#

I wanted to implement it as a webapp (using python on the backend obviously), that's probably why I dropped it. At that time I knew almost nothing about back-end development 😅

queen axle
#

lol

#

oh and server_handler should be called client_handler

open isle
#

ok yeah it's hanging on my machine too

#

time for more debugging

queen axle
#

it seems like it's kicking the client

#

try removing the exceptions

#

or commenting them out for now

#

oh wait seems like it's failing on the server or something

#

I GOT IT

#

your method worked

open isle
#

what was the issue, I'm still debugging 😅

queen axle
#

so after I edited everything to include that "header", I forgot to choose the byteorder on the server side, and the try and excepts were hiding it

open isle
#

oh lol whoops

queen axle
#

that was probably my fault actually

#

also it seems like using cd doesn't work when entering the command line

open isle
#

nah that was my fault, I should've double checked before dropping that argument

#

apparently a default for byteorder was only added in 3.11

queen axle
#

ah

#

damn versions

open isle
#

are you on windows, cd is a shell command on linux and the command is failing on my machine

queen axle
#

I spent about 30 minutes trying to figure out why my stuff wasn't working, just to remember that launching the python bin defaults to python2 on linux

queen axle
open isle
#

it does, but on Windows the code turns on shell mode automatically

#

I'mma turn that on always

queen axle
#

lol bash ftw

open isle
#

yup

queen axle
#

bash is one of my favorite languages

#

has the coolest syntax, people who have never used bash will look at it like if it were some shit from the year 3023

open isle
#

it isn't crashing on my end, but ls isn't showing the entries I'm expecting after cd

#

oh WAIT, that's because each subprocess is independent of each other

queen axle
#

¯_(ツ)_/¯

#

I'm using Windows 10

open isle
#

cd won't work as expected because it only affects the current working directory of the subprocess call with ["cd", "somepath"]

queen axle
#

ah

#

I realized that

#

because it wouldn't let me change directories, and noticed the directory I was in was the same one where the server is located

open isle
#

yup

#

trying to search for a way to run a command in the parent process's context, but I can't find anything, everything starts a new process or similar

#

not even sure OSes allow you do that

#

presumably not since the shell linked with the process is already "blocked" running whatever command the process used to start

queen axle
#

it's fine, it's possible to use relative or obsolete paths

#

using dir or ls

#

just put a disclaimer note on the client lmao

open isle
#

I guess the proper way to implement a SSH server would be to keep a single subprocess around and mess with its stdout/stderr/stdin streams directly, but I don't want to think about that. Sounds hard.

queen axle
#

doesn't sound easy lol

#

anyways, what were you saying about \n and +1 earlier?

open isle
#

if you take len() of just the subprocess.stdout, the receiver won't read the extra \n you're adding before sending the output

#

well actually it might depending on how the data arrives, but it's not guaranteed and things might break

queen axle
#

wow, you're right

open isle
#

but if does not get read, then the next call to recv() will first read b"\n" and then the first three bytes of the header which will mess up the length calculation

queen axle
#

I just removed the '\n' in the server and it hangs up the client

open isle
#

yeah because it's expecting one more byte

queen axle
#

kind of complicated to understand but it makes sense

#

I'm sure it's easier to understand with a graph or a diagram

#

oh I get it now

open isle
#

Yeah me too, I'm happy to create one but that'll take a bit. In the meanwhile, one more suggestion:

You should break out the message sending logic into a separate function since

except FileNotFoundError:
    conn.sendall(b"Command not found.\n")

doesn't follow the expected format (there's no header!)

queen axle
#

good idea

#

ah and I think it might be a good idea to make this all into a class

#

hmm but python classes aren't as advanced as the ones in c++

short trellis
#

Hello
i need help .
How can i receive data from server using irc lib?

queen axle
open isle
#

that's up to you, I generally prefer to avoid classes except for simple record-like classes

#

but it can be a nice way to contain the logic

queen axle
short trellis
queen axle
#

doesn't sound hard tbh

#

all scripts automate a task

open isle
# open isle Yeah me too, I'm happy to create one but that'll take a bit. In the meanwhile, o...
def send_message(conn, message):
    if isinstance(message, str):
        message = message.encode()
    message_len = len(message)
    conn.sendall(message_len.to_bytes(4, "big"))
    conn.sendall(message)

here's an example, this is nice because you can append the newline before the len() call, so + 1 isn't necessary anymore

send_message(conn, command_out + "\n")
# or
send_message(conn, b"Command not found.\n")
#

anyway do you need anymore help @queen axle ?

queen axle
#

do u recommend anything easy to use?

open isle
#

lol of course, last time I touched that was 3 years ago

queen axle
#

alright cool

#

ah I've used this before, yeah it's easy to use

#

how strong is it, do you know?

#

ah wait nvm, it all depends if you have the key or not

open isle
queen axle
#

we went from bash to processes to encryption

brisk hawk
#

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((IP_Address, PORT))
print('Connection established, key and hostname incomming')
s.send(f'{hostname} : {key}'.encode('utf-8'))
print('Data sent successfully')
s.close()

#

So I have this as sockets connecting to a server.

#

is it possible to add an error code if the server isnt running?

#

I tried this

#

tried
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP_Address, PORT))
print('Connection established, key and hostname incomming')
s.send(f'{hostname} : {key}'.encode('utf-8'))
print('Data sent successfully')
s.close()
except socket.error:
print("Connection failed)

open isle
remote citrus
leaden pike
#

Hi guys, I'm making a Server Proxy with python I got information about create that, but using http and I need https, anybody know?

hollow jackal
#

hi i want to learn about servers any source?

zealous flint
#

From a high level a server is really not much different from the computer you may be on right now

#

It usually has all of the same components and can even run the same software and OS

hollow jackal
#

i have a old android mobile i want to convert it into a server in which i can run my website / discord bot / script

errant tangle
queen axle
#

anyone here know how to make the socket library's connect() method act similarly to the hanging of listen()?
when listen() is called, the program hangs into a blocking mode until it receives a packet, I need the same "hanging" to happen with connect(), so the client will always be trying to connect to the server continuously, I've gotten this to work but is there a better way to instead have the request to the server only be sent once, and the request will always be waiting and won't die until the server accepts it?

ember ledge
#

Is this about hacking?

unreal wren
#

No, hacking is boring and takes ages, imagine manually converting a entire finance company’s paper data sheets to a excel doc with a crappy keyboard and the keyboard sometime doesn’t work.

#

Hacking is a Hollywood way to describe a programmer that is about as accurate as the guy in the public bathroom who sucks at peeing in a urnal, so pretty bad

lucid spruce
#

I've been working on creating a wrapper library for a graphql API lately, and found it very tedious to create a python class for every Type one can find in the GraphQL API as well as storing the graphql query string for each type. I'd like to be able to define the types found in the API as a dataclass, then have a function that creates a string query out of that. I've looked into pydantic, apischema, graphql-core and gql, but none of them seem to achieve what I'm looking for. I've also found some smaller projects but these aren't as fully developed or reliable for future updates. Therefore I would like to create my own library. Before I go all out and start developing this, is there anything I should be aware of? Does it seem like a good idea? I've written examples of how I would like the end-product to be in the README of this project:
https://github.com/BeatsuDev/GraphQLRequests/tree/alternative-solution

GitHub

Contribute to BeatsuDev/GraphQLRequests development by creating an account on GitHub.

hollow jackal
errant tangle
errant tangle
hollow jackal
patent knot
#

hi, i want to know that does warp block open network captive portals.

ember ledge
#

I can't really understand the functioning of the accept() method in socket. Like i see it used many times in server programs tutorials in while True loops, with some lines of sending and receiving after the call of it. But following the logic if there's no client that connects to that server, the lines of sending and receiving are even so running within the same loop cycle. Why does it work? I mean if nobody is connected and we send data to nowhere (because the socket used to send and receive data from a possible to/from a possible client has not be created) it should throw an error or something am i right?

#

So do the line about sending or receiving bytes only work when the preceding call to accept() has returned some info about a connecting client?

#

I'm completely new to python networking so tell me if i'm saying bs

prisma cobalt
#

if no client connects, the code will hang until a client connects

ember ledge
#

Wow okay that makes sense

dusk slate
#

Can anyone help explain why I'm getting this error code as a response, when I'm defining the Network function on line 3?

#

this is my first networking endeavor, pls be gentle 🥲

#

if it helps, this is the tutorial i'm following, with the timestamp set to where they're teaching the part:
https://youtu.be/McoDjOCb2Zo?t=2653

This Python online game tutorial will show you how to code a scaleable multiplayer game with python using sockets/networking and pygame. You will learn how to deploy your game so that people anywhere around the world can play against each other.

You will learn and understand the following after this tutorial:
• How a Client/Server System Works
...

▶ Play video
dry geyser
#

you can't create an instance of a class before that class is defined

#

!e ```py
class Class:
xyz = Class()

errant bayBOT
#

@dry geyser :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 2, in Class
004 | NameError: name 'Class' is not defined
dry geyser
#

the class hasn't been created yet so you can't make instances of it

#

perhaps you meant to do ```py
class Class:
def init(self):
print("whatever")

xyz = Class()```

dusk slate
dry geyser
#

see how line 19 is indented?

#

that means that it is inside of the class

#

if you unindent it then it will be outside of the class

dusk slate
#

I do now, wow thank you so much for breaking that down!!

dry geyser
#

np

fallow hill
#
    import subprocess

    filename = "image1.jpg"
    model = "../yolov5/carsModel.pt"
    saveFolder = "Images"


    cmd = "python " + detectPy + " --weights " + model + " --img 640 --conf 0.25 --source " + uploadFolder + \
        filename + " --project " + outputFolder + \
        " --name " + saveFolder + " --exist-ok --save-txt --save-conf"
    p = subprocess.Popen(cmd, shell=True)

I have this subprocess cmd that works well on my flask app when ran locally. But when I host it on https://dashboard.render.com/, it just gives me an EOF on the screen when I run it. What should I do with it?

Cloud Application Hosting for Developers | Render

Render is a unified cloud to build and run all your apps and websites with free SSL, global CDN, private networks and automatic deploys from Git.

ember ledge
#

hi, is there a way to figure out the optimal timing value to use for a timeout for some process?

lilac orbit
#

guess and pray

paper sage
#

using a wifi card in a virtual machine to use in monitor mode in made by Bridge Network?

ember ledge
#

I can't really understand the functioning of the accept() method in socket. Like i see it used many times in server programs tutorials in while True loops, with some lines of sending and receiving after the call of it. But following the logic if there's no client that connects to that server, the lines of sending and receiving are even so running within the same loop cycle. Why does it work? I mean if nobody is connected and we send data to nowhere (because the socket used to send and receive data from a possible to/from a possible client has not be created) it should throw an error or something am i right?

storm saffron
#

accept blocks until a connection starts

#

so if there is no client to communicate with, the code after socket.accept will not run until there is

sterile beacon
#

Does anyone have experience with libraries for web based online games in flask? I looked into flask socket io for connecting clients and server. This is for a project where i through a web application controls robots stationed somewhere. Do you guys have any good suggestions on how to stream live video data from an external camera/phone on the robot -> server -> to a specific client? And possibly embed the videos on the client. Some materials i could read 🙂

silk summit
#

Hi all. I'm having a problem with python+udp code, which works fine on linux, but doesn't on mac (probably binding both the tx and rx port). Plus sometimes getting duplicate packets to app layer using
data = self.receive_socket(self.rs)
Even though tcpdump/wireshark showing no dupes.

These problems may be related?

ember ledge
#

I have question about the while loop in this piece of code

#

(my difficulty in understanding probably stems from the fact that I don't know much about threading)

#

why isn't the threading at the beginning of the loop? I know it's used to handle multiple clients at once, but why does it create the threads right where it sends them to the handle_client function instead where it accepts them at client, address = server,accept()

steady horizon
#

The main thread handles the accepting new clients part. The handling of each client is thrown into its own thread, so everything is in its own thread and everything runs concurrently

ember ledge
ember ledge
silk summit
#

Yeah I agree. What would the point in binding to the transmit port?

ember ledge
silk summit
#

Why would you need to bind to it (tx)? Sample code for trivial udp client/server doesn’t. I understand why rx does

ember ledge
#

you're right

#

like i said im not an expert just yet thats why im giving you simple answers, wish i could've helped more

silk summit
#

All good bro

steady horizon
# ember ledge does this this mean that it can't accept multiple clients concurrently? Like in ...

Does this mean that it can't accept multiple clients concurrently?
Correct. But one at a time suffices for the most part. Some servers run multiple listening threads or even processes to accept a greater deal of clients at a time.
In the process of one client being thrown into its own thread, can it not accept clients during this time?
Correct, accepting clients and starting the handling threads are two different calls in the main thread, but after starting a thread, it doesn't block the main thread in a well behaving program.
How does socket decide which clients to accept?
I think there's something called a backlog in the listen function, it limits something but I don't know what. Other than that, clients connect to the other side of the socket which is bound to an address and port. Sockets are just the individual connection of two socket.socket objects from different programs.
In what situations could it obtain a client's IP and port but not be able to communicate with it?
If the other end of the socket shuts down its reading/writing stuff, you can't have it do those from its end. I don't know whether getsockname requires any of those to be permitted, but the socket connection is all that's needed to know addresses of both ends (because there is a connection). Other than that, you get the other socket end's address from the return value/values of the accept method

ornate sluice
#

How can I make a collaborative text editor?

#

Would fastapi be enough?

#

Or flask

elder cobalt
#

Uhh, is anyone here familiar with PyDivert? (Python implementation of WinDivert) I'm trying to find if it's possible to send ICMP packets to my router with it

#

Or would scapy do the job much easier?

opal arch
#

Hello how can i build a sniffer using python

steady horizon
real hearth
#

It was not for production use. I needed HTTPS for local testing. Some OIDC servers require the callback url to have https schema instead of just http (even for localhost)
Ex: https://localhost:8080

unique sluice
#

Hi, I've a camera for monitoring and it has something called HTTP POST where I can setup address, port and heartbeat which it can be connected to. It can send some info in xml format - for example alarms.
I've created a socket server and I can get this info. Is there a better way to manage this connection?

zealous flint
#

!d requests

errant bayBOT
#

This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation.

unique sluice
# errant bay

OK, and how to listen to the data on IP:port using requests?

near nexus
#

Hey guys I'm trying to teach myself python, for ethical hacking. Where I am now stuck at is. I am allowed to do other things at work as long as its like on my phone. So I have been reading a few books, and trying to get a understanding. While i know its better to program on a pc, but dont have one with me while at work. So when book tells me to write a TCP/UDP client, and Im supposed to run it and wait for the data and servers response. Should I do this in Termux, cause I have tried a few IDE but no response ever comes back.

silk summit
#

You’re probably going to have a bunch of odd limitations on termux, but I never used it. Don’t you have work to do at work?

ember ledge
#

can semeone tell me like a basic ipv4 stresser/offliner code becouse i lost mine when i resetted my pc and im trying to learn coding!

river hare
#

im using ftputil, is there an easy way to enter a directory

#

i cant find anything about it 😭

river hare
#

figured it out lol

surreal spade
#
import socket
from threading import Thread

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(False)
s.settimeout(10)
host = socket.gethostname()
port = 7777
size = 512

def write_message(conn):
    message = input(str('\n<<< (You): \n'))
    if message == 'bye':
        conn.close()
    conn.send(message.encode())

def receive_message(conn):
    while 1:
        try:
            if conn.fileno() == -1:
                break
            message_recv = conn.recv(1024)
            if not message_recv:
                conn.close()
                break
            print('\n>>>', message_recv.decode())
            print('\n<<< (You):')
        except socket.timeout:
            pass
    conn.close()



def chat_session(s, is_server = False):
    global host, port
    if is_server:
        s.bind((host, port))
        s.listen(1)
        print("Waiting for incoming connections...")
        conn, _ = s.accept()
        host, port = conn.getpeername()
        print(f"Connection from {host}")
    else:
        s.connect((host, port))
        print("Connected to the server!")
        conn = s
    while 1:
        Thread(target=receive_message, args=(conn,)).start()
        write_message(conn)
        choice = input('[1] Continue, [2] Switch Mode, [3] Exit: ')
        if choice == '2':
            host = input("Enter new IP address: ")
            port = int(input("Enter new port number: "))
            is_server = not is_server
            conn.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setblocking(False)
            s.settimeout(10)
            break
        elif choice == '3':
            conn.close()
            exit()
    if choice != '3':
        chat_session(s, is_server)

choice = input('([1] for make connection or [2] for wait connection): ')

print("To exit the chat, type: bye or CTRL + C.\n")

if choice == '1':
    chat_session(s, False)

if choice == '2':
    chat_session(s, True)```
#

hey, hey im not sure where i'm going wrong. im having a problem when i try to switch from a client to a server

#

im getting an OSError: [WinError 10038] An operation was attempted on something that is not a socket Traceback (most recent call last):

bright sparrow
#

does anyone know how to enable monitor mode on windows 10?

ember ledge
storm saffron
#

as in the traceback

sweet nest
#

could i say that a tree topology is a good example of network segmentation?/

lilac orbit
prisma cobalt
#

try switching the order of the if statement and the last line

fringe aurora
#

just wanna ask, is there any way for me to send emails using smtplib ? back then it always let me send emails with programs using it but as of recently google did smth and i cant send them anymore using smtplib

#

i read that i gotta enable less secure apps in order to send emails using smtplib but

#

option is no longer available, any clues?

rapid fog
#

I think you need to use the official gmail API

finite dock
#

anyone use ciscoconfigparse and napalm? cant get both installed one breaks the other :/

leaden pike
#

Hi guys, I'm using requests_ip_rotator on my scrapper, but when I try to put access_key_id and access_key_secret I get this error: botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the GetRestApis operation: User: arn:aws:iam::{UserIam} is not authorized to perform: apigateway:GET on resource: arn:aws:apigateway:us-east-1::/restapis because no permissions boundary allows the apigateway:GET action

#

any idea?

normal sentinel
#

hi guys, i'm here to ask you some help for a project i have in class. I have to do a program that separate networks in subnets. The user has to choose between separate by how many hosts on each subnets or how many subnets wanted. I dont have any idea how to do that so i really need help pls...

sorry for my english, i'm trash in this language

finite dock
ember ledge
#
import requests

url = "https://panel.socialheaven.xyz/api/v1/"
key = {'key':'7HUq1G5E6tVoIE5ikevj'}
action = {'action':'add'}


x = requests.post(url, json = key, add, )

print(x.text)
ember ledge
#

hello

#

is there anyway to take two packets coming in on a socket and separate them into diffrent sections of a list

ember ledge
#

Hi, is it possible using python3 asyncio.Protocol to get notified of a connection inside a seperate class other than the one i also receive in?

#
import asyncio
from src.client import Client

class ClientSession(asyncio.Protocol):

    def __init__(self, loop):
        self._clients = {}
        self.loop = loop

    def data_received(self, data):
        print(data)

    def connection_made(self, transport):
        self.transport = transport
        index = len(self._clients.keys())
        print(index)
        self._clients[index] = Client(transport)

    def connection_lost(self, exception):
        if exception is not None:
            print("Got exception: {}".format(exception))

class ClientListner:
#

I wanna put the connection_made into the ClientListner class instead

#

How would i do this?

ember ledge
#

Someone know how i do so its download a file to spesefic Path?

proven granite
#

Hello everyone, before learning Django, are there any concepts or anything I should learn or know?

sullen burrow
#

Good day guys, is there a library or way to do an ip rotation??

lilac orbit
#

import socket
import threading
from datetime import datetime
from queue import Queue

print_lock=threading.Lock()

host=input("remote host")
ip=socket.gethostbyname(host)

print(" you smell")
print("MRGORT says you smell// scanning host")

#

thoughts

ember ledge
#

This doesn't resolve the public ip address

lilac orbit
dry tundra
#

Any recommendations on OpenSearch client libraries?

stray galleon
#

is there anyone who know where to get insta dm bots or know how to make them if you do please shoot me a dm

lilac orbit
#

Don’t do that, it’s scummy and unethical.

stray galleon
lilac orbit
#

Oh

stray galleon
#

im using it so i dont have to copy and paste tell them

zealous flint
ember ledge
zealous flint
ember ledge
wise jungle
#

@cloud spruce where are u

lilac orbit
#

'''imports'''
import socket
from datetime import datetime
import threading
from queue import Queue

print_lock = threading.Lock()

host = input("Remote Host: ")
ip = socket.gethostbyname(host)

print("-" * 80)
print("scanning"
"the"
"host - -------> ", ip)
print("-" * 80)

t1 = datetime.now()

def scan(port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, port))
if result == 0:

        print("\n Port %d Is Open!!!!!!!!!!!!!" % (port))
        sock.close()
    else:
        print("\n Port %d Is Close  " % (port))

except:
    pass

def threader():
while True:
worker = q.get()

    scan(worker)

    q.task_done()

q = Queue()

for x in range(60):
t = threading.Thread(target=threader)

t.daemon = True

t.start()

for worker in range(1, 100):
q.put(worker)

q.join()

t2 = datetime.now()

total = t2 - t1

print('Scanning Completed in: ', total)

#

@ember ledge

ember ledge
lilac orbit
#

I’ll try it in the future, threading was just the faster and easier route, im far more comfortable with threading than multiplexing

ember ledge
lilac orbit
#

I’m not looking to scan all of the ports, if I wanted to do that I would be using an extension of nmap and scapy. I just made this for fun. If I ever need to scan 65,000 tcp ports I’ll find a way to work around inactive and filtered ports.

#

Even then nmap only Scans for the most common 1000 ports per scan. I

mighty niche
#

Hi

placid tree
#

Hi, I have a question. For SSL VPN do I have to use the vendor provided client?

placid tree
#

Another question:
I have to connect to two servers on two different remote networks at the same subnet via SSL VPN. Is this possible? If yes can I just add route rules and be fine with it?

acoustic ether
#

How can I receive all of ICMP packets via socket? using

socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)

I can only receive packets of type echo-request, timestamp-request, information-request, and address-mask-request

fathom rover
#

Hi

#

How to use pywinrm with work account

ember ledge
#

how do i make a webserver thats listening to port 2000 dm me to help

storm shard
ember ledge
#

no cause i use this hosting thing

lofty bough
#

It's kind of embarrassing that I can't find this myself...

hazy widget
#

An RFC would have an "updated by" or "obsoleted by" header if it weren't the latest

lofty bough
#

ah

#

makes sense, thanks

hazy widget
#

But you might want to look at 1123

#

Possibly even 2821

lofty bough
#

as I understand, there's also some separate RFC for the actual email headers and such?

#

and for ESMTP extensions

hazy widget
#

821 is referenced in there...

#

and 822

#

Section 10 has a load of references

lofty bough
#

🤔 those are like twice as old as me

hazy widget
#

[9] Newman, C., "ESMTP and LMTP Transmission Types Registration",
RFC 3848, July 2004.

#

SMTP's been around a while.

#

Oh, I missed:

Updated by: 7504

#

...but that's only additional messages, it seems

lofty bough
#

arrrr why is it so complicated

hazy widget
#

It might be best to start with 821, and then the later RFCs might make a little more sense

#

Reading RFCs is a skill in itself :)

lofty bough
#

💀

#

it was supposed to be a fun project...

hazy widget
#

There may be a more accessible SMTP howto out there, although if you can read the RFC, it'll be the most correct resource

lofty bough
#

I know the gist, and I have sent emails manually via telnet before

#

I mainly wanted to know the details to implement a server, and the extensions that are considered "mandatory" nowadays

hazy widget
#

HELO, EHLO(?), MAIL FROM, RCPT TO, DATA would seem to be minimalistic.

#

Back to the suggestions of how to approach a project - don't aim too high to start. get something simple working to get your motivation up and then work out what the next steps are from there. If you have read the RFC to understand those commands, the next steps might become more apparent after implementing the basics.

#

As soon as your next steps become chores, your decision is: am I doing this for fun only and need to stop, or do I want to work through this and see it to completion. ;)

main hamlet
#

I just dug out an old project with intend to refine it but it behave in weird way, as tested in Windows it spit out all IP, now when I moved to Linux it spit localhost, "ip a" is listing 3 proper IPs when code 3 times localhost

from socket import getaddrinfo, AF_INET, gethostname
current_ip_addresses = ""
for ip in getaddrinfo(host=gethostname(), port=None, family=AF_INET):
current_ip_addresses = current_ip_addresses + ip[4][0] + " "
print(current_ip_addresses)

output:
*127.0.1.1 127.0.1.1 127.0.1.1 *

any idea why?

rose silo
#

anyone need networking help gotchu

zealous flint
#

Networking class be killing me

zealous flint
#

Nice! Though I was just joking 😛

#

Glad to have you around here though

#

Maybe you can be the next rndpk

rose silo
#

ahaha

#

thats a never

restive grotto
#

icmp dosnt have a socket as such

#

A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number.

#

icmp is the 3rd type protocol flag, its neither udp or tcp

fallow oasis
#

yo how do you make a socket client terminal able to write commands in while its connected to a socket server?

#

is that even possible?

finite dock
#

anyone have regex patterns match interface names for long to short, or short to long?
ie, GigabitEthernet0/1 to gi0/1.
vise versa ofcourse and with possible interfaces such as 1/0/4

#

i mean to check 1 and change to the other.

zealous flint
#

What are the different short formats it can be in?

Gi0/1
G0/1
G 0/1
That's all, right?

finite dock
#

not 3rd.. but also gi0/1/0 format

#

can be upper g or lower g

#

and yes, cisco devices

#

trying to match patterns in logs, as most people will shorthand interfaces when submitting changes to an interface.. so it shows up in log that way, and i want to match the log entries for that interface, which ciscos log by whole name.

zealous flint
#

@finite dock looks like it can really be any amount of starting letters

finite dock
#

tru, but its not normal for someome to type more wether fa/01, gi0/23, te0/1/1, etc

#

same with int for that matter.. int, inter, interace

zealous flint
#

Hmmm 🤔

finite dock
#

it autocompletes.. you ever press tab when typing?

zealous flint
#

haven't tried on packet tracer lol

finite dock
#

it should i would guess..

zealous flint
#

an elegant regex pattern is not immediately obvious to me here

finite dock
#

btw.. consider gns3.. they gave it python support.

zealous flint
#

What is that?

finite dock
#

another simulator like packet tracer.. only caveat is you need a real cisco image to build the routers

zealous flint
#

Ah, I see
We're using packet tracer in school so i'm just more familiar with that

finite dock
#

np.. backbuner it.. have a better idea for you..

#

go get a free cisco devnet account, you can fire up labs that have no simulator bugs.

zealous flint
#

I'll keep it in mind 😄 Thanks for the suggestion

finite dock
#

btw.. the labs you can vpn into, to test automation apps like ansible, genie, etc.

high delta
#

i'm trying to mount a remote system
i heard about sshfs
basically it has a setup.py file but i don't want to copy the entire structure over to my pc
but i do want it to run as if it were on my pc
anyone know how I can do this?

ember ledge
ember ledge
#

Hello, does anyone know how to create a perceptron in python? help me please

blazing igloo
#

What have you tried? @ember ledge

normal oyster
#

Hi

blazing igloo
#

Hello there.

restive grotto
final meteor
#

How do I learn to understand packets captured by wireshark? I know the osi model but I don't understand every single field/flag of each layer. How do I get to the point where I can tell wether it's streaming video data or sending data through a socket?

zealous flint
final meteor
zealous flint
#

No, unfortunately 🙁

final meteor
halcyon hornet
halcyon hornet
#

you're welcome 😄

placid tree
#

I have to create multiple Ipsec tunnels but remote tunnels have the same subnet of 10.10.10.0/24. Should I create static endpoint routes rather than subnet routes? Would this solution work?

#

Our company is MSSP and we have to talk to a single server in every customers network

hidden mango
#

can anyone here be a mentor
[3:14 PM]
i really wanna get started and if you do youd have one more person for any personal projects your working on
[3:14 PM]
just add and or message me if you see this

prisma cobalt
#

how is that related to network @hidden mango ?

thorny bobcat
#

I'm configuring a firewall on my VPS but I still want my discord bot to work.
I'm trying to figure out which firewall rules I need to add.

As far I understand I need to allow internet traffic to discord.com.
These are the IP addresses discord has registered for discord.com:
162.159.135.232
162.159.136.232
162.159.137.232
162.159.138.232
162.159.128.233

I've tried allowing incoming and outgoing TCP traffic from any of those IP addresses to any port.
However my bot was unresponsive after enabling the firewall.

Anyone knows what I need to change / add?

prisma cobalt
thorny bobcat
#

The reason I want to apply a firewall is because I don't want anyone except me and some others to be able to see a website and interact with it.
I'm going to add a login system later on but for now I'm happy with just whitelisting some IP's.

Would allowing any inbound and outbound traffic to any port except for port 80 (it's http website) and then whitelisting those IP's for port 80 accomplish the same goal without adding any more security concerns?

thorny bobcat
#

Never mind allowing outgoing connections and then configuring incoming how I like did work.
Apparently the vps is down for 2 ish minutes after applying a new firewall

fast basalt
#

hi'

#

can someone help me

storm saffron
#

?ask

#

!ask

errant bayBOT
#

Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

storm saffron
#

pls

merry hornet
#

Can someone here help me estimate how much it would cost to do a project or how long for a complete newb to do it?

storm saffron
#

what's the project

naive warren
zealous flint
merry hornet
#

@naive warren @storm saffron creating an API with no programming knowledge but high intuition using chat gpt and tutorials that will scrape a similar website to zillow for all of the individual links to apartment listings, and then based off of the data in the individual listings (price, amount of rooms, area etc.) it will manually make pairs of the links into a google sheet that has clients names and numbers, as well as data about them that is relevant (price, amount of rooms, area etc.).

#

and also how much would it cost to potentially hire a developer to do this

naive warren
#

well, depending on other requirements, I would charge something between $200k to $5mil to do that

merry hornet
zealous flint
#

priorities

naive warren
#

I suspect legal fees alone would be on the order of $200k for what HardTwerker described

fast basalt
#

anyone here good wit networking

zealous flint
muted panther
#

Is there a fiddlerscript wrapper for Python?

fast basalt
#

my hero

#

so the problem is my code

#
if __name__ == "__main__":
    init()
    Name: str = input("Your username: ")
    C = Client('localhost', 4000, name = Name)

    while True:
        DATA = input("Message: ")
        timeout(1) # type: ignore
        C.send_message(f'[{Name}]: {DATA}')
        timeout(0.4) # type: ignore
        print(C.recv_message())
        

Client side above

Server below

import socket

Clients = []

def _server():
    Network = socket.socket(
        socket.AF_INET,
        socket.SOCK_STREAM
    )

    HOST: str = "localhost"
    PORT: int = 4000

    Network.bind((HOST, PORT))

    Network.listen(100)

    while True:
        C, A = Network.accept()
        Clients.append(C)
        __import__('time').sleep(0.5)
        try:
            DATA_RECV = C.recv(1024).decode()
            C.send(DATA_RECV.encode())
        except Exception as err:
            Clients.remove(C)
            with open('errorLog.log', 'w') as fw:
                fw.write(str(err))
                fw.close()

The problem is that it will only send 1 message then freeze server does go online but when you send a message it works but only 1 time

#

@zealous flint

mystic pagoda
#

When using netmiko to push configs I’m struggling with implementing the send command timer via ConnectHandler. Using web sources but still no luck. Anyone got examples to share?

misty zinc
#

Are there any pcap parsers for USBpcap files? I've tried scapy but it seems to be capped at parsing 65535 bytes and my pcap file contains packets with sizes of over 1MB.

#

I found KaitaiStruct but it looks like the author only provided some kind of baseline instead of a proper library.

#

Of course, if there's a way to extend scapy's capabilities to parse larger packets, I could work with that too.

sharp sundial
#

Hey so question. I’m reading python crash course currently, but I’m wondering, when should I sort of pivot into focusing on network automation? Like is there specific material I should read on the subject? Or should I read this here book “automate the boring stuff” next?

pearl anchor
#

does anyone know how i can get the right TXT dns record?

ember ledge
#

Who is hosting your DNS records?

pearl anchor
#

hi, could i ask for help on port forwarding my uvicorn app? im running the backend on "0.0.0.0" which points to the local ip of my computer, and i've set up a port forward rule for the same local ip and port which is running the server. The frontend picks up the requests on my computer which is running the server, but on my phone or non-wifi users, the request times out, could someone help me understand what the issue is?

prisma cobalt
prisma cobalt
#

What do you type in your browser's address bar?

pearl anchor
#

my vercel app's url

prisma cobalt
#

Ah so you have a URL, are you certain that it points to your public IP address?

pearl anchor
#

if you actually read the question, im pinging the backend through the frontnend, uvicorn is running on 0.0.0.0 which means local and its running on port 443 which means https

#

the server is port forwarded and vercel frontend is working when i run it on my pc

#

but if i use the vercel app on any other device other than the computer thats running the server, the request times out

#

the vercel app isnt running on local host, its running on vercel server

prisma cobalt
#

How are you connecting to the backend from the frontend?

pearl anchor
#

im not, its just requesting the backend through axios

prisma cobalt
#

That's connecting to the backend, if it's not working you've either set up the port forwarding rule incorrectly or you're not connecting to the right address.

pearl anchor
#

bro pointing out the most obvious outcomes

#

the port forward works, the backend is able to take incoming requests from the vercel app which isnt on my computer

#

but only on my computer

#

im starting to think theres some issue with my windows not letting requests from outside of my computer inside

#

ppl kept talking about tweaking the firewall or somthing

prisma cobalt
#

the backend is able to take incoming requests from the vercel app which isnt on my computer
but only on my computer
what? you've contradicted yourself

pearl anchor
#

how

#

if u use it

#

it wont work, the request will time out

#

if i use it on my phone

#

it wont work, the request will time out

#

but weirdly, if i use the vercel app on my computer which is hosting the backend

#

the requests can comm

prisma cobalt
#

show me the axios code that makes the request
also can you send a screenshot of how you've configured the port forwarding rule

pearl anchor
#

we gotta go into dms for sharing sss

prisma cobalt
#

thats fine

pearl anchor
#

dont trust 80k ppl with an ip addy

prisma cobalt
storm saffron
prisma cobalt
stark smelt
#

Hello everyone, can I ask a question about PyModbusTCP.client? I am struggling with some settings regarding the 'Response time' setting and I can't get through it.

simple sequoia
#

If i use my school WIFI which is a unsecured network, can they see my photos/videos and or messages? If they can, does it only work when i go on the photos app?The only thing i would be doing is watching youtube or tiktok,
im confused about this since nothing will be encrypted but if im only on tiktok or youtube thats the only thing they should be able to see im on right?

zealous flint
#

Unless you transmit them over the network

pearl anchor
# prisma cobalt Yeah lmao

Lmao what, it literally wasn't the right answer, unicorn is bound to local ip, whatchu mean that was the right answer

prisma cobalt
#

It wouldn't have worked with the local IP anyway so we fixed something

pearl anchor
#

nah, axios didnt reach the public ip cos the backend is scope bound to local network, despite being hosted on port 443

#

i even set a port forward map but nothing changed

molten carbon
#

If I were to write a VPN, what libraries do I need, and where to begin?
I'm trying to write a VPN to use a VPS I have as the VPN
I also want to make sure I'm gonna use a stable protocol
How do I figure it out?

molten carbon
#

Also uh stupid question but
what is each IPv4/v6 section called
like
127.0.0.1
what is each number between the dots called?

zealous flint
zealous flint
#

I've self hosted my own VPNs before and they aren't too bad

molten carbon
#

Tho I prefer not to use a known protocol (WSTunnel etc) given how my country is very strict about detecting them

zealous flint
#

You won't need to "write" anything

molten carbon
#

write as in a client

#

protcol can't be written exactly

zealous flint
#

Have you looked into OpenVPN?

molten carbon
#

OpenVPN gets frequently blocked here

zealous flint
#

That's attributed to the actual protocol being used

#

I don't believe openvpn is a protocol in and of itself

molten carbon
#

I meant when I use all the protocols it just doesn't work

#

not that the app itself gets blocked ofc

zealous flint
#

There aren't really that many VPN protocols out there

#

If the well known and strong ones are getting block, the lesser known ones even more so

molten carbon
#

Well I'm hoping if I can use a TCP protocol and the server is unknown

#

maybe they won't notice

zealous flint
#

That's pretty much what openVPN does

molten carbon
#

Alright fair enough

#

ty

#

@zealous flint Is the SMTP reliable at all?
I've heard they can't block it yet but I'm not entirely sure

#

sorry not SMTP

zealous flint
molten carbon
#

uh

#

for some reason I mistook it with SMTP

#

lemme look up the name again

zealous flint
#

We're you thinking of SNMB?

molten carbon
#

not it was a protocol that apparently microsoft introduced

molten carbon
#

SSTP

urban depot
#

What is Network Function Virtualization

#

or NFV

lethal shadow
#

Hello, I am new to networking and was building a packet sniffer using scapy. I am processing the pcap file and running a loop on it like this

#

`def packet_sniffer():
packets = rdpcap("tcpudp.pcap")

for packet in packets:
    print(packet.summary())
    converting_to_bytes = bytes(packet)

    e = Ether(converting_to_bytes)
    e_src_add = e.src
    e_type = e.type`
#

But when I print the e_src_add I get 4 address as the output

#

where I need only one. And the file has 4 packets in it

#

Can anyone please help me with this.

ember ledge
#

Can someone tell me how to use tcp ip

zealous flint
ember ledge
zealous flint
#

You're on Discord, using the HTTPS protocol

ember ledge
zealous flint
# ember ledge What is the https protocol, and how does it work?

HTTP(S) protocol is based off the HTTP protocol, the "s" standing for "secure"
HTTP is used for exchanging websites and also text
It can be quite complex, read the RFC if you so wish: https://www.rfc-editor.org/rfc/rfc9110.html

#

It resides on the application layer of the TCP/IP model

ember ledge
zealous flint
#

Technical specification details on many protocols are available as RFCs

ember ledge
#

Can somone help me depoly my api (in flask) online so other people can use it

hollow mirage
#

after that just monitor your API

ember ledge
storm saffron
tranquil sonnet
#

Not python, but look at all this freaking regex I had to build grumpchib

#

I have ascended into godhood

broken urchin
#

I'm guessing this falls under networking. I have a websockets server setup and an async queue handler function. In the async queue handler function it is broadcasting to all connected clients. I'm just testing so there is only the 1 client and it's just printing what is on the queue to the screen however the server throwing TypeError. I don't know why it keeps throwing the TypeError message when I have a client connected. Any ideas what I'm doing wrong?

    async def websocket_add_client_handler(self,websocket):
        self.websocket_connections.add(websocket)
        try:
            await websocket.wait_closed()
        finally:
            self.websocket_connections.remove(websocket)

    async def queue_handler(self):
        while self.Stream_Run:
            msg = await self.stream_queue.get()
.....
           if self.websocket_server is not None and len(self.websocket_connections) != 0:
                try:
                    await websockets.broadcast(self.websocket_connections, str(msg))
                except TypeError as e:
                    self.logger.error(f"Error websocket broadcast: {e}")
                    pass

async def main(self)
....
        if self.websocket_handler_address is not None:
            self.websocket_server = await websockets.serve(self.websocket_add_client_handler,self.websocket_handler_address, 8765)
tranquil sonnet
#

can you post the error?

broken urchin
tranquil sonnet
#

hard to tell from your code, but I would say put a except TypeError as e: just before the finally at the top

#

see if that narrows it down

broken urchin
#

SOLVED: In case anyone was wondering, no need to await websockets.broadcast apparently.

So I was reading the docs about the broadcast method here:
https://websockets.readthedocs.io/en/stable/reference/utilities.html#websockets.broadcast
It talks about:
RAISES
RuntimeError – if a connection is busy sending a fragmented message.
TypeError – if message doesn’t have a supported type.

So I was thinking perhaps the msg was an unsupported type even though I'm casting it to str so I added a check shown below but it never hit it yet is still reaching the except TypeError as e: block.

if type(str(msg)) not in (str, bytes):
    self.logger.error(f"Error: unsupported message type: {type(str(msg))}")
    self.logger.error(f"Message: {str(msg)}")
    continue
try:
    await websockets.broadcast(self.websocket_connections, str(msg))
except TypeError as e:
    self.logger.error(f"An error occurred while handling the websocket broadcast: {e}")
    pass
#

I am wondering if I am overflowing the client buffer or something. The simple test client is just:

import asyncio
import websockets
import socket

async def receive_data():
    HostIPAddr = 'localhost'
    try:
        async with websockets.connect(f'ws://{HostIPAddr}:8765') as websocket:
            print(await websocket.recv())
            while True:
                data = await websocket.recv()
                print(data)
    except Exception as e:
        print(e)

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(receive_data())
    loop.run_forever()
#

since the client is printing to the screen I am wondering if it's too slow??

ember ledge
zealous flint
ember ledge
zealous flint
azure forge
#

im using the sockets package and the socket will only use http in the url, I cannot get it to use websocket protocol

async def main(): 
  async with websockets.serve(get_clip_bytes, "localhost", 8765):
    await asyncio.Future()

asyncio.run(main())
#

this is a code snippet

#

of what im doing

fast basalt
#

May someone help me

azure forge
heavy jasper
#

I am currently learning python in my class , and we have been given a research work , basically a big exercise , I wondered if someone here is familiar with paramiko , and could help me in dm or call for like 10-15 minutes , since I could not find my answers on google or youtube for the last 4 days , ty very much !

dawn trout
#

Hello, I am trying to move a python script i have on my hp laptop to my macbook laptop. I need help figuring out what i need to change to satisfy the switch.

#

This is the error that I get

azure forge
#

the issue was that I was typing localhost in websockets.serve

#

inputting a blank string worked

pale monolith
#

made this, a proxy server. Socks5 in python. Please let me know if i can improve anything https://paste.zluqe.com/sitasutuku

Easily share and store your code snippets and notes with our user-friendly bin service. Secure, fast, and reliable.

ember ledge
#

can someone explain why time complexity is O(1) for this crossbar using switches configuration? suppose P1 is accessing M1, and P2 is waiting to access M1 also so is P3 and now P4 has to wait for p1 and p2 then p3 to finish to access so time complexity should be O(n)

static tangle
#

is there any way to host a website from a pc with only the ip address and not using any domain?

static tangle
#

@frozen iris

fallow oasis
#

yo how can you stream wave files through a socket connection with io.bytesio?

#

im kinda lost at that point

storm saffron
#

you cut out the line number when you posted the error

broken urchin
fallow oasis
# storm saffron what have you tried

i was pretty dumb to try to play the audio files on the server, but i solved it later tho since i discovered io.BytesIO() and just used it within the socket connection

void nova
#

anyone know and want to explain to me why (working) proxies will refuse to connect/site will not send any data/other

polar schooner
ember ledge
#

thanks

final meteor
#

How is for example a youtube video transported over the internet? What protocol etc

bitter salmon
#

Is getting a IT networking diploma a good idea

dry geyser
lethal pawn
#

Not sure if this is the right place to ask, how can I produce any of the error codes from 500, 502, 503, or 504 using requests?

#

If I am able to produce any one of the error code it would help me a lot

ocean bay
#

Or you can whip up your own http server and send a request there

final meteor
gloomy root
#

This is how HLS works which is what systems like Youtube, Twitch, etc... use

fallow oasis
#

how can you possibly make this wave output able to be sent through a socket connection? Im trying to send this data by .sendall() but it wont really work.

This is from the client.

with wave.open(new_file, 'rb') as wave_file:
    params = wave_file.getparams()

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

        s.connect((host, password))
        s.sendall(params)

This is the output of "params":
https://cdn.discordapp.com/attachments/1075248428638023720/1075248458925080668/image.png

#

It just give errors that says that it needs to be a bytes like object

final meteor
#

Could anyone explain why packet loss causes duplicate acknowledgements? Why would the client send multiple acknowledgements?

gritty kernel
#

does anyone of you know if pybluez works on python 3.11 with windows 11? and if not, are there any better bluetooth libraries/frameworks right now?

wise jungle
fallow oasis
#

your*

mystic girder
# fallow oasis i actually found a way with pickle but thank you for help anyway!

try not to use pickle if you don't trust the other party (i.e. some random users sending you a pickle instead of yourself)

this is a massive security issue since it's possible to construct a pickle maliciously such that it runs python arbitrary upon unpacking it - see the official docs here https://docs.python.org/3/library/pickle.html#:~:text=Warning The pickle module is not secure. Only unpickle data you trust and a demonstration here https://checkoway.net/musings/pickle/

viscid lava
#

anyone here used pyserial?

#

I cant seem to get it working here, sadly

native pier
#

Guys could you help me on how to ignore SSL certificate verify with python sockets ?

#

seems like i constantly get this error : Failed to connect to KuCoin. Error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)

quaint crystal
#

Hi everyone, does anyone here have a Scapy habit?
I'm replaying all the packages I want, I see them pass on Wireshark but there is no reaction from the devices I'm trying to attack. I replay modbus packets. It doesn't matter if I play them directly or if I play them by reading a pcap. I can't figure out the issue.
Thanks!

ember ledge
#

nice; amazing work

final meteor
#

Does anyone know why there are characters in the wireshark tcp stream that are not valid base64 characters? The data being sent over is base64 encoded

dry geyser
#

it's possible that you're looking at the encrypted or compressed version of the base64 data

#

or you're looking at the wrong (section of a) request

heavy bloom
#

gm

ember ledge
#

with QUIC how do I install aioQUIC?

#

because I do pip3 install aioquic and it doesn't work?

ember ledge
#

can someone tell me whats the most important network-modules are?

final meteor
#
HTTP/1.1 200 OK
Server: Werkzeug/2.2.2 Python/3.9.2
Date: Mon, 19 Dec 2022 13:21:14 GMT
Content-Disposition: attachment; filename=fjhsde9832hsa87adj
Content-Type: application/octet-stream
Content-Length: 2058
Cache-Control: no-cache, max-age=0
Expires: Mon, 19 Dec 2022 13:21:14 GMT
Date: Mon, 19 Dec 2022 13:21:14 GMT
Connection: close

.B.....B.....B.....B.W...1....fB....XB..e..C..d.QB..c..B.....B.....B.....A...p.@..|..C....f@..l.oC%...f@..l.oA%...f@..l.oG%...f@..l.oE..m..A..d.fE..m    .G.....B..d.nN..d.fB..}.f@..l
.B..d.nM..d.fB..}.fJ..d
.K....fI..d..I..}.fL.....C+....F+....E+.f
fM.....L..d..B%.d.fV(.}.~G..|.hS..j..@<../.R....~O
...~J$....C..|..C
...~C.....B..|..U.....B....fW
.}.~P..k..C.5|
~R/.\..Q..n.~P..k..C.....[$.|..Z.....@.....W..|..X$.|.~W/....@.....T..j.~T..d..@..|.._..|..@.....C..|    .B....vW.....@..|..B..|.~R.....B.]|.~I....p......B....~R..d..C
.d..B
...~R..|..C..n.~P..k..C..|..U.....B<.q..C..W.fB.....A..n.3B<.s.2B.....B....fB..).L8.6I..B..)..A.RS*...ESB+Cv.gfv..vngm/.uywg1....r#...vl2.s)..O.ntfq..x_om,..
om,.Htl] .cep.C...R.C...b.C...a.C...r.C.....C....+@..euk..yewk{...`.B.....B.....B.....B....q......&...~...s...?.......k...&.....&...~.......>.k.....j...>.....>.......j..

If this is what an Http stream looks like in wireshark, what does doing .content in python on the response get? Is it just the encrypted data?

chilly knoll
#

Hi guys, I'm trying to build a trading AI software, I need to speak with someone with good expertise in the field please.

cobalt raven
#

Hi everyone,

I have a semi-abandoned project I want to present to you all.
Perhaps there is someone who has some fresh ideas to pull it afloat.
It's a web based game...

https://exodus2200.pythonanywhere.com/

Any feedback is welcome, but also if you feel like working with me on it, please don't hesitate to contact me..

Kind regards,

Alex

runic shale
#

I have a quick question. Im new to networking and I think im doing something extremely wrong. Im sending whole json strings over the sockets. How should I do that instead?

crimson torrent
#

ok not sure if this is the righlt place to ask but im writing a small http server app using pythons BaseHTTPRequestHandler/ HTTPServer classes and on post back I'm reading the post back with cgi like this, it says however cgi will be deprecated in the next point release of python, how should I be doing it now??

Current way i read the form vars

form = cgi.FieldStorage(fp=self.rfile, headers=self.headers,environ={'REQUEST_METHOD': 'POST'})
print ("BLAH: " + form.getvalue("blah"))

steady horizon
#

If you need to make a post request, you can simply use urllib.request.urlopen and pass a urllib.request.Request object instead of a str for url

zealous flint
crimson torrent
steady horizon
#

Is cgi a necessary part of your app?

latent vortex
#

this is a bit of an odd question but im streaming video from one device to another, despite both being connected to the same internet connection via ethernet i get a insane amount of latency with every single movement, i cant check it but it feels atleast in the 100s, which for a device located 5 meters away from me is too much, anyone have an idea why?

zealous flint
latent vortex
zealous flint
#

Everything has latency

#

Medium, processing time, host computational power

latent vortex
# zealous flint Everything has latency

well other people who are doing the same thing as me don't get these problems and the latency is VERY high btw not acceptable for something which is a room away

zealous flint
#

What's the bitrate of your network?

#

Router specs? Host specs?

crimson torrent
crimson torrent
latent vortex
# crimson torrent low spec device that is working its arse off to capture and encode the video buf...

Well it's a bit embarrassing to say this but it's not a complicated server or anything but just my PC and PS4, I've tried Steam Link ( PC runs games, streams it to mobile devices ) it runs like absolute garbage, then i tried PS Remote Play and the same there, it doesn't matter what i do, even both being on Ethernet connection it's very unstable and ugly looking, i hear it's something related to my router settings but the answers on Google are just too complicated and idk what the issue really is

#

They work flawlessly for my friends in different countries, and they get confused when i say mine has latency, they say I'm stupid there should be no latency when it's hosted in my house

zealous flint
latent vortex
buoyant isle
#

How to check if packets with UDP was sent in correct order with socket programming? How do I do that in python?

steady horizon
ember ledge
#

hey! I have a list of ips, and i want a script that can take a list of ips, and ping them so that they send back their description, kind of like shodan.io, but instead of searching for ips i want it to give a description on the ones i already have.

#

<@&267630620367257601>

zealous flint
ember ledge
#

i believe so, the hosts are minecraft servers, im trying to find a script that allows me to upload a bunch of ips and then get the desciption player count etc sent back

zealous flint
#

I don't believe Minecraft servers use the traditional ICMP protocol

#

There are APIs out there that will do this for you

ember ledge
#

such as?

#

i couldnt find one 😦

zealous flint
#

I've used this one a few times

ember ledge
#

oh my gosh thank you so much

ember ledge
zealous flint
#

I don't believe so

#

Not aware of ones that ping with a whole list

ember ledge
#

ok

#

i have a list of about 4700 ips i need to check

ember ledge
opal lotus
#

Does anyone know how to resolve the "network is unreachable" error when trying to access google SMTP server from my web host?

#

I assume its blocking it but I dont have any sort of firewall access to change that. And support won't answer

zealous flint
opal lotus
#

when i try to ping in terminal it says icmp open socket operation not permitted... ugh

ember ledge
#

oh

#

thats what you were saying

#

gotcha

#

hmm

#

im stuck

wicked swallow
#

i am trying to build a ping system,
I am using ICMP,

    print(receivedPacket)
    icmpHeaderLength = 8
    packetSize = len(receivedPacket) + icmpHeaderLength

this is where i calculate packet size, but in wireshark its showing a packet length of 106

b'E`\x00\\x00\x00\x00\x00v\x01\xf21\x8e\xfa\xb3\xee\nY\x04\xce\x00\x00\xbb\x8d\x00\x00\x01\x00\xdc\xae\x82\x9e&\xfe\xd8AQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ'
100 bytes from google.com (142.250.179.238): ttl=118 time=0.02 ms

fair cape
zealous flint
fair cape
#

<@&267630620367257601>

#

i was about to ping the admins and then i realized that would actually ping them lol

zealous flint
#

Yeah if it shows up in the ping menu then you know it will actually ping

#

If it doesn't show up the popup as you're typing then it doesn't ping

fair cape
#

i just used <&role_id>

lethal shadow
#

Hey, I was implementing switches and bridges using mininet vm. I wrote the program using nano editor. When I run the program as sudo python proj3.py in another line mininet> opens what should I do. I am really new to mininet. Can anyone please help me with this.

prisma lance
#

Is python actually any good for networking

cunning garden
prisma lance
#

It’s more of a data science/machine learning language no?

prisma cobalt
#

@prisma lance it's very good for networking at a high and low level I'd argue, for example, Netflix uses it across the board to serve content and if I remember right (and this may be wrong) but I believe it's used in some major air traffic controls settings

#

Sockets are cool

red radish
#

Heyo, learning python, I'm trying to read the response headers from an api im connecting to and this documentation says you can just print r.headers...but I get the headers I sent not the other way around...is there an object to see the headers sent back as that contains request timeout info and whatnot

steady horizon
#

Can you send your code?

lilac orbit
lilac orbit
red radish
#

def get_assets(assets, r = requests.Session):
r = requests.Session()
client_params = {
"action": "list",
}
r = vActiveSession.post(url=vPlatformURL + vListAssetsURL,headers=vClientHeader,params=client_params)
if r.status_code == 200:
assets = json.dumps(xmltodict.parse(r.text))
f = open("Assets.json", "w")
f.write(assets)
f.close
return assets, r
else:
sys.exit("Get Assets: " + str(r.status_code))

def main():

Qualys.login(vActiveSession)
Qualys.get_assets(vActiveSession,vAssetJson)
Qualys.logout(vActiveSession)
print(str(vAssetJson.get("HOST_LIST_OUTPUT","BUSTED")))
print("Yay!!!!")

main()

#

For some reason it isnt passing the r from get_assets back to vAssetJson

#

they both get declared above vActiveSession = requests.Session()
vAssetJson = {}

steady horizon
#

The function always creates its own session if you notice in its first line

#

Also the name of that session is overshadowed with the response later on... And you probably meant to have r: requests.Session not r = requests.Session in the parameter list

red radish
#

OMG - That's from older iterations of it. This is my first time doing python and my end goal is api integrations with security tools that lack features

#

Trying it now

steady horizon
red radish
#

but im calling that outside of the function

steady horizon
#

I know, but in your function definition you're using vActiveSession and not the session paramter of the function

#

You have r = vActiveSession.post(...

red radish
#

ohh i get you, fixed that

#

That part was working though at least haha, but you're right

#

Oh yeah, is there a "best practice" method for writing logs or is open() enough?

steady horizon
#

!d logging

errant bayBOT
#

Source code: Lib/logging/__init__.py...

red radish
#

nice....

steady horizon
red radish
#

this is such a rabbit hole of joy

#

wish id done it years ago

uncut arch
#

Can anyone help me to write program for idle scannig, together on github?

tough stone
restive crown
#

I can't manage to upload a file to colabcode fastapi
I'll pay 30$ to whoever helps me in private

errant bayBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

steady horizon
#

sorry wait let me get this

errant bayBOT
#

9. Do not offer or ask for paid work of any kind.

restive crown
#

malicious?

steady horizon
restive crown
#

it's a dumb rule

#

I hate the government

ember ledge
#

guys I'm running a script with dns.resolver to get IPs associated to URLs but the script is not finding anything (No A records for the URLs).

Yet if I use nslookup or any other web app that resolves URLs, an IP is returned.

#

What gives?

#

I'm using the same nameserver in the script and in my pc settings: 8.8.8.8

uncut arch
prisma cobalt
prisma cobalt
errant bayBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

lilac orbit
restive crown
uncut arch
prisma cobalt
#

Port scanning can be used to identify vulnerabilities in public networks as well

tulip belfry
#

@frigid cedar I was about to reply to your question but it closed. Anyway, wanted to suggest you to check all the headers that the browser uses, because you might need more than just user agent - see here for example https://stackoverflow.com/a/34166756

frigid cedar
rose bridge
#

Hey guys! I am looking for developers who are interested in ai generated art, people who are trying to host their own models. Anyone interested in a chat?

lilac orbit
#

Tmr I plan on streaming to break down and code a udp scanner, talk about network scanners the uses and implementations into network security, port spoofing, probe mitigation and different types of scans and what we can do to mitigate probing attacks on home networks through the use of disabling ports

#

If anyone would like to tune in, shoot me a dm and I will send a message when we are ready to go

lilac orbit
dry geyser
#

illegal? in what jurisdiction?

#

you can use portscanning to perform lots of other illegal activities, but to my knowledge the portscanning process itself is not illegal, on any network, in the united states

#

maybe the network owner would get mad at you and fire you if they were your employer or kick you out if they were mcdonalds

lilac orbit
#

Udp scans are intrusive scans and deemed illegal if run on a private network without consent from the isp or owner

#

In the context of the United States

dry geyser
#

do you happen to have a source for that? I just haven't ever heard of such a thing

lilac orbit
#

Yes

dry geyser
#

after a brief scan through, it looks like that article is actually saying the opposite

#

that port scanning on its own is in fact not illegal

lilac orbit
#

It says by technicality it is a breach of the law

dry geyser
#

So is port scanning legal? The short and rather unhelpful answer is “it’s complicated”

However, a June 2021 Supreme Court decision, Van Buren, might be good news for security researchers. In that case, the court held that mere violation of access restrictions is not necessarily an offense. Rather, the prohibition is limited to someone who “accesses a computer with authorization but then obtains information located in particular areas of the computer – such as files, folders or databases that are off limits to him”.
This decision has only just been handed down, so it remains to be seen how it is interpreted. However, it may establish the principle that simply pinging or port scanning a network and nothing else, is not actionable.

dry geyser
#

Takeaway points
Several years ago, US Department of Justice Special Counsel Leonard Bailey gave advice at the Black Hat conference on how to stay out of trouble. The advice probably holds up well in lots of jurisdictions: “If you’re pinging a network, that’s not actionable. If you’re port-scanning, again, not a problem unless you’re doing it at a denial-of-service level. Beyond that, you may get questions.”

lilac orbit
#

While the intent of the law is to prosecute malicious hackers, its ambiguity has long posed a potential problem for security experts. On a strict reading of the Act, If you use port scanning on a network without the owner's consent, then technically, you are in breach of the law.Dec 19, 2022

dry geyser
#

interesting, didn't see that part

#

looks like it has never been enforced for port scanning though

lilac orbit
#

You won’t get arrested for it but it technically is illegal

#

The government could really care less about ddosing and network manipulation, unless you start messing with government sites and networks

uncut arch
#

This project is just a skill training project, my friends, I don't want to attack anywhere, Nmap itself has the Idle Scan tool, and at the same time, the US government uses Nmap...
If anyone wants to help me with this project, let me know

lusty raven
#

I need you guys advice

#

It would be better to get advice from someone who sucessfully have made server that can handle large amounts of connections

#

can this code handle 100 clients trying to receive message from server every 10s

#

There will be a single server as mentioned in code that will be sending text to whoever connects to 6942 port

#

while client would be fetching message from 6942 every 10s

#

Can I be sure 100 clients connecting every 10s wont create very large lags

#

Is there a way to benchmark that after how many clients connection things will start to get slow

#

Is there a way I can modify the code to become less laggy or something

lusty raven
#

Tested it out

#

Created 100 clients as subprocess under screen

#

if sleep == 0

#

other than that if sleep is every 10s its working fine

mild yew
#

while trying to create a script to ssh into every switch on my network, I get an IO error. any ideas?

sudden pivot
#

Anyone knows a method to receive data from clients constantly in socket? Without while

placid kelp
mint star
#

Currently when I return a video file with fastAPI it is unseekable in the browser how do I fix that?

turbid sonnet
#

.

ember ledge
#

sockets problem for me

#

can someone help

final meteor
#

Could anyone explain the encryption used on Tor? Does the originating computer set up a different key with each of the nodes and then encrypts the message in the proper order?

final meteor
#

nvm i got it

scarlet plover
#

anyone familiar with the ipaddress module
trying to ping scan two different networks but trying to avoid having to build two different tests

currently i'm doing a

networks = 
ipaddress.ip_network("192.168.0.0/24", "192.168.128.0/24")

for host in networks.hosts():
    ping(str(host))

but not able to parse the second one
i know i could do a

networks = 
ipaddress.ip_network("192.168.0.0/24")

networks2 = 
ipaddress.ip_network("192.168.128.0/24")

for host in networks.hosts():
    ping(str(host))

for host in networks2.hosts():
    ping(str(host))

but thats hella bloody ugly

scarlet plover
#

i created a list with two networks in it and wrapped the for loop in for each network, its better though i still think has room for improvement, but i guess it works so theres that

ember ledge
#

does anyone know how to send data to websocket

quasi widget
#

!pypi websocket-client @ember ledge

errant bayBOT
faint beacon
#

Got experience in lightweight 2d game programming, and figured it was a dead end seing how the languages community is dying out.

So i figured i wanted to learn something new. Im new to networking, and looking for a deepdive tutorial that has depth. Any recomendations?

I cba the bits and pieces of 'tutors', then puzzling it together. What im looking for is a dense tutorial.

heady saddle
#

hi I have a question about the google CalendarAPI. I can create events, load the events as a dict but when I try to update them it goes wrong.
This is a (part of ) my script:

start_time = datetime.datetime.now(pytz.UTC)
lessons = net.get_schedule()
now = datetime.datetime.now(pytz.UTC)
range_start = now.isoformat("T",timespec='seconds')
range_end = lessons[-1][1]
calendar_checklist = {}   # dict with events from google <start time> = <[end time, title, event_id]>
pageToken = None
while True:
    events_online =service_calendar.events().list(calendarId=calendar_id, timeMin=range_start, timeMax=range_end, pageToken=pageToken).execute()
    for i,event in enumerate(events_online['items']):
        calendar_checklist[event['start']['dateTime'].replace('Z','+00:00')] = [event['end']['dateTime'].replace('Z','+00:00'),event['summary'], event['id']]
    pageToken = events_online.get('nextPageToken', None)
    if not pageToken:
        break
calendar_diff = []    # new lessons
calendar_upd = []     # updated lessons
for lesson in lessons:
    if lesson[0] in calendar_checklist:

        if lesson[2] != calendar_checklist[lesson[0]][1]:
            calendar_upd.append([calendar_checklist[lesson[0]][2],lesson[2]])
            print(calendar_checklist[lesson[0]][2])
    else:
        calendar_diff.append(lesson)

for i in calendar_upd:
        response = service_calendar.events().update(calendarId=calendar_id, eventId=i[0], body={'summary': i[1]})```

It runs without error, but the update does not go trough. `net.get_schedule()` returns a list. These are example elements from that list
```python
["2023-03-09T07:40:+00:00","2023-03-09T08:30:+00:00","Nederlands"]
["2023-03-09T08:30:+00:00","2023-03-09T09:20:+00:00","Frans"]
steady horizon
#

The HTTP/1.1 protocol is made so you read until line endings (\r\n). The request line and each header all terminate with a line ending. Then follows another line ending. Then follows the data of the length of Content-Length (the number of bytes of the data)

coarse snow
#

I need to interact with the gqrx SDR server for getting and setting frequencies.

How would I accomplish this in python?


#PseudoCode

frequency_to_tune_to = 10000000

telnet_connection = valid_python_library(open telnet on 127.0.0.1 port 7356)
telnet_connection.write('f') # "lower case f is a command that will return current frequency")
print(telnet_connection.read())
#expected result is: "1021000", this is the last tuned freq I was on
telnet_connection.write(f'F {frequency_to_tune_to}') # upper case "F" does not get frequency, but instead SETS frequency. This is the protocol as it stands in the software I'm using.

What libraries would you utilize to approach this problem and would you be willing to write an example with said library? I'm not even sure where to start looking, I've looked at telnetlib3 and would like to avoid the headache of asyncio at the moment because I don't particularly understand it or how it will interact, I'm willing to use it with good enough examples though. I'm just coming up dry on searches on how to interact with a protocol over telnet.

coarse snow
#

Exscript is failing to import hard, and I can't seem to find a good tutorial for telnetlib3

plucky pond
#

How to duplicate this meme in python

#

Need this for uuuuh

#

Reasons

sudden pivot
#

Anyone knows a library for creating servers?

placid kelp
#

a http server?

#

a ftp server?

#

a dhcp server?

#

regardless, i doubt you'd use a python library for "creating" a "server"

#

you'd use existing software that runs on a physical server

#

like nginx

zealous flint
keen peak
#
DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(PATH)
#

I got this error on my selenium python project

#

Idk what it means and google is not helping much

polar sky
ember ledge
#

@polar sky What are we looing at here?

#

Looks like spanning-tree LOL it warms my heart

keen peak
zealous flint
#

spanning tree protocol my beloved

polar sky
keen peak
#

So you could write your code like this
tree.mx = value
tree.child = value

polar sky
#

honestly using the class function and using nested listing has little to no difference depending on how you use the lists

#

i just find it easier using lists due to being able to append much eaiser and being able to locate things with for loops much faster using tree[x]

keen peak
#

I mean you could just have a list of tree objects
list = [tree1, tree2, tree3, tree4]
list.append(tree(mx, my..))

#

but the app still looks pretty cool

polar sky
loud monolith
#

Hello, basically I have a problem where the code behaves different than what I want it to,

I have 3 classes, 1 parent class and 2 child class for the same parent class

this is my parent class:
https://paste.pythondiscord.com/oromeqacok

these are my child classes:

Child class number 1: (AKA client handler)
Child classes:

class AudioRC_Client(AudioRC_Server):

    def __init__(self, sock, connection_info, conn, addr):
        super().__init__(sock, )
        self.connection_info = connection_info
        self.conn = conn
        self.addr = addr
        self.connections = {'client': self.conn, 'remote': None}

    def identify(self):
        ...
        self.add_client(conn)
        ...

Child class number 2: (AKA Remote handler)

class AudioRC_Remote(AudioRC_Server):

    def __init__(self, sock, connection_info, conn, addr):
        super().__init__(sock, )
        self.connection_info = connection_info
        self.conn = conn
        self.addr = addr
        self.connections = {'client': None, 'remote': self.conn}

    def login(self):
        # this is the place I want to be able to access the self.clients variable, altoguh its empty - even after the changes were made in the client's class

        print(self.clients)  # Output: []

The code works fine, until I want to access self.clients
it shows an empty list even after I called the self.add_client(), I can access it through the child client class, but not through the remote class

thats probably related to what I am doing at lines 41 and 29, where I start new instances for my child classes - which inherit the parent class, but I want it to behave as if the parent class's variables and functions are sync and the variable's values on one child class, are the same variables and values on the other child class...

Thanks in advance and I hope you understand what I was trying to explain

pulsar axle
storm saffron
#

are you instantiating an AudioRC_Client instance and a AudioRC_Remote instance?

loud monolith
#

to handle server side of each, remotes, and clients

storm saffron
#

but are you doing what i said

#

could you send your full code

errant bayBOT
loud monolith
storm saffron
#

i think you should try to find some resources on oop/inheritance basics and applications

#

you seem to expect that altering the attributes of one instance will change another instance because they both inherit from the same class

loud monolith
#

what can I do then?

brave jetty
#

Are there any libraries for connecting and working with openthread APIs?

wicked kelp
#

We were searching for something like FastAPI for the Kafka-based service we were developing, but couldn’t find anything similar. So we shamelessly made one by reusing beloved paradigms from FastAPI and we shamelessly named it FastKafka. The point was to set the expectations right - you get pretty much what you would expect: function decorators for consumers and producers with type hints specifying Pydantic classes for JSON encoding/decoding, automatic message routing to Kafka brokers and documentation generation.

Please take a look and tell us how to make it better. Our goal is to make using it as easy as possible for someone with experience with FastAPI.

https://github.com/airtai/fastkafka

GitHub

FastKafka is a powerful and easy-to-use Python library for building asynchronous web services that interact with Kafka topics. Built on top of Pydantic, AIOKafka and AsyncAPI, FastKafka simplifies ...

loud monolith
#

hello, How can I publicly host my socket over my public address?

finite trellis
#

I can't really find this anywhere, but for the OpenSoundControl Protocol:
From my understanding, it uses /things/like/this to actually direct packets to things, if I create my own OSC server using https://pypi.org/project/python-osc/, will I be able to listen to any calls to the /things/lile/this path?

zealous flint
#

But be warned because port forwarding can be dangerous

loud monolith
zealous flint
#

Did you give them your private IP?

loud monolith
#

I am first trying it on myself with my public IP

#

but it doesn't work

#

which I already have opened in my windows firewall

zealous flint
#

Which port?

loud monolith
#

I can dm you my ip if you want

zealous flint
#

that won't be necessary. I trust you know the difference between public and private IPs

loud monolith
#

I do

zealous flint
#

8466 is the same port the socket is listening on?

loud monolith
#

for the server, I did

IP = '127.0.0.1'
PORT = 8466

and on the client I did my public IP and same port

#

also tried to put my domain, which redirects to my public IP

zealous flint
#

Ah I don't believe you can set the IP to that

#

That would only listen on localhost

#

Similar issues happen with Flask and FastAPI

loud monolith
#

so for IP i do local host?

zealous flint
#

Try 0.0.0.0

loud monolith
#

sec

loud monolith
wicked kelp
#

We were searching for something like FastAPI for Kafka-based service we were developing, but couldn’t find anything similar. So we shamelessly made one by reusing beloved paradigms from FastAPI and we shamelessly named it FastKafka. The point was to set the expectations right - you get pretty much what you would expect: function decorators for consumers and producers with type hints specifying Pydantic classes for JSON encoding/decoding, automatic message routing to Kafka brokers and documentation generation.

Please take a look and tell us how to make it better. Our goal is to make using it as easy as possible for someone with experience with FastAPI.

https://github.com/airtai/fastkafka

GitHub

FastKafka is a powerful and easy-to-use Python library for building asynchronous web services that interact with Kafka topics. Built on top of Pydantic, AIOKafka and AsyncAPI, FastKafka simplifies ...

wintry musk
#

I have a question about named pipe (FIFO) and local socket. Can a single socket handle multiple operations at the same time ?

For example, let's say a client executable is making 2 requests at the same time through a local socket. The first request will take 2sec to complete, the second will take 1sec. What I want to know : will the second requests by answered before the first one ?

toxic mural
wintry musk
#

@toxic mural in my case it can be either a named pipe (on windows) or a domain socket.

toxic mural
#

oh sorry, i have no knowledge about windows named pipes .(

gleaming hull
#

I have a task to analyse a trace of ospf packets (.pcap file). The thing is i need to get information about the topology of the network by getting Link IDs, Metric for each link, and the two router IDs for each link i.e. information about the links between OSPF routers. Which type of packet am i supposed to be looking at? I know there are hello packets, database description packets, link state requests, link state updates and link state acknowledgements.

zealous flint
#

Wire shark has an OSPF display filter

naive kite
lost chasm
gleaming hull
# zealous flint https://www.wireshark.org/docs/dfref/o/ospf.html

Thanks, btw anyone knowledgable in ospf? I had a question regarding some routing information i was provided, and i’ve been told about some paths which are invalid and others which are not (given some path they made). I am not understanding why though some paths are invalid and while others are not (can’t seem to find a valid path given the routing information).

#

Would prefer if i could dm

turbid shale
#

@remote citrus it's in italian Indirizzo = address

remote citrus
#

mm

#

tbh not too sure what it wants 😅

turbid shale
#

I'm gonna retry putting my public ip in there and lan ip in the lan section

#

🤷‍♀️

#

cause connecting to the server from the server itself (same network) works fine

#

then I tried doing it from a vm and I got connection refused

#

not sure how network works in vm so maybe that's the problem?

#

ssh sshuser@publicIP -p 22 -> connection refused lemon_angrysad

turbid shale
#

Using port forwarding, access to the IP and port(s) assigned to the WAN is forwarded to a host on the LAN.
This feature allows users to access LAN virtual hosts over the WAN.
In particular, when the initial value of the ""WAN Port"" field is set to 0, the ""WAN Port"" and ""LAN Host Port"" parameters will automatically use 1-65535.
The "Remote Host IP Address" field allows you to define a Range of IP addresses of the source of the incoming packets, in the form Initial_IP_Address-Final_IP_Address.
The value 0.0.0.0-0.0.0.0 means any IP address.
@next jasper here's the explanation the isp provides

#

I don't really get it since I'm braindead

#

never mind I got it. I suppose that's just the range of IPs I will use to connect to the server, some sort of whitelist

#

leaving it blank works

next jasper
# turbid shale <@314334182111182848> it's in italian Indirizzo = address

This doesn't seem like port forwarding, it seems more like just allowing ssh access to the router itself or something? Especially with the "Indirizzo IP Host Remoti" being a range, it looks more like "which ip range is permitted to access this" rather than actually forwarding.

Just find some general port forwarding settings, not any section like that. Like I showed you from my router

Also, consider changing the language if you can't find stuff - sometimes translations are way off

next jasper
#

Okay, so I think I know

turbid shale
#

the dropdown says SSH just because I named it that. It's actually internet -> security -> portforwarding

#

btw even though the server and the client have python installed, when running a file from the client I get the python is not a recognized command :P

next jasper
# turbid shale <@314334182111182848> it's in italian Indirizzo = address

The range thing -> set to 0s like the instruction says but make sure you ssh settings are secure because you might get random ips trying to attack you
Host LAN + Porta host LAN -> ip + 22
Porta WAN -> what port will be used with router's IP (all ports from that range will be used to access the same thing if Porta LAN is non-zero).

Porta LAN being 0 means "forward all", that's why range is 1-65535 by default. At least I guess it works like that

next jasper
turbid shale
#

mhm when I try to run it with py it says it doesn't find a python installation, but I do have python on the server

#

the server is windows and client is linux btw

#

running on my server:
C:\Users\dbuon>py
Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

running the same from the client
sshuser@PC_NAME C:\Users\dbuon>py

No installed Python found!

next jasper
#

I'd check where is that python installation. Might be some weird location and the sshd is somehow limited from accessing it? Or just py lacks some env variables that it normally does - it would be nice to pinpoint what happens so we could either report the issue with py or find how to easily patch it.

I don't normally use python on my Windows VM (I have 7 python versions on my host system XD) and I only ssh to that VM to port forward stuff, so I never encountered this.

ivory ridge
#

How can i send data through wifi using UDP in Python ?

ember ledge
#

hey guys how can click button on website using requests moduke... pls help

pallid compass
shadow heath
#

Has anyone ever tried to setup a small webserver in python that uses the QUIC protocol?

#

Just for simulation, not for real use

loud monolith
#

What's the best way to handle the connection after this suddenly shows after long period of time?

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond```
#

this closes the connection, anything I can do to keep the connection?

#

the connection timeout showed up exactly 2 hours after the last server even

loud monolith
oak swallow
#

hey hello

#

weird question but

#

is anyone here able to help with entity relationship diagrams?

toxic mural
loud monolith
toxic mural
#

yeah, but you can't really "keep" it in that sense. sure, TimeoutError is the exception to catch

tough delta
#

oh really

drifting glade
#

I use requests.get() in my code and it works, but after I hosted my application, an error appeared:
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain
I tried to fix it like this, but it still doesn't work:
...

        with open("cert.pem", "w", encoding="utf8") as f:
            f.write(os.getenv("PEM").replace(r"\n", "\n"))
        os.environ["REQUESTS_CA_BUNDLE"] = 'cert.pem'
        os.environ["SSL_CERT_FILE"] = 'cert.pem'```
...
`session.verify = "cert.pem"`
What can I do?
#

I received the pem file via firefox, replaced the line break with \n in it and placed it in env

rustic pollen
#

how can i ue socketio in python

#

and integrate to fast api

toxic mural
# drifting glade I use `requests.get()` in my code and it works, but after I hosted my applicatio...

the remote server you're sending the request to with requests.get, is it controlled by you? I'm assuming not
the verify attribute seems correct. https://stackoverflow.com/questions/30405867/how-to-get-python-requests-to-trust-a-self-signed-ssl-certificate according to this you can try passing verify="cert.pem" explicitly to the line where you're sending the request

drifting glade
toxic mural
#

is cert.pem readable for your process? what happens if you pass verify="somenonexistentfile" to double check that you get an error if ti's not?

toxic mural
#

are you sure that the line of code raising the error is the line where you're passing verify=?

drifting glade
#

Yes

toxic mural
#

okay

#

after rereading this:

        with open("cert.pem", "w", encoding="utf8") as f:
            f.write(os.getenv("PEM").replace(r"\n", "\n"))

can you double-check that cert.pem contains what it originally contained when you downloaded it?

drifting glade
toxic mural
# drifting glade yes, it contains the same

sorry, I thought about it a bit more but I'm mostly out of ideas 😦
do you have curl installed (you should, it's a great tool!)? you could try requesting the URL with `

curl --cacert cert.pem https://.....
young vale
#

so i was wondering is it good to use 4 processors then 1? cause i saw a yt video saying it boosts your performance and stuff so i went to run and typed in msconfig and then i went to “Boot” and selected “Advanced options” where it said”Numbers of processors” do i have it on max or 1?

rustic pollen
#

can anyone here teach me websokets library i ant to master the library

dusty garden
#

I was wondering if there was a way to add another value to the read_sockets variable. For example, valid username. If I was able to add that, how would I then check the value in an if statement for example

prisma cobalt
#

the read_sockets variable is a list of sockets that are available to read from without blocking (theres data ready to be read).

#

@dusty garden

#

you can add a value to the list with append but im not sure that adding a "valid username" to that list is what you want to do

dusty garden
#

I tried using append but it didn't allow it :(

#

This is the code I currently have. Most is from a tutorial and I am just trying to build on it myself to see if it would be a feasible programming project. Currently, the client script sends its username and password and the server checks it against a database. If it is incorrect it returns an error to the client and asks them to try again however whenever it tries to send information back, it just gets stuck on line 76 and won't do anything. I'm a bit confused

umbral zinc
#

I have .pcap file from class and we are supposed to look for a singular malicious traffic, and the teacher said it would be "obviously" out of place but I haven't found anything like that yet, or just some suspicious things but most are just dead ends and some are to throw you off? We are using wireshark for the analysis btw, is there anything that I could look at for more or something I'm particularly overlooking?

umbral zinc
#

not clicking that 💀

undone flint
#

It’s from ietf website

#

It’s evil bit

#

If teacher say it obviously out of place and there no more context maybe could be that

umbral zinc
#

the "client" said they are experiencing bandwith issues

undone flint
#

Look for lots of the same packets

#

It say singular malicious traffic though that can’t cause bandwidth issues

loud monolith
zealous flint
rustic pollen
#

anyone has a knowledge in websockets?

#

why do i et this error

"websockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK)"

#

what doeos this mean

steady orchid
#

Hello I have trouble implementing a python socket chat system for a multiplayer cli game I am building.
This is the server code related to that:

#Server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

ipaddr = "127.0.0.1"
port = int(8888)

try:
  server.bind((ipaddr, port))
except socket.error as er:
  str(er)
server.listen(100)

def send_message(un, sn, msg, t):
    return json.dumps({
            "status": 200,
            "type": t,
            "data": {
              "username": un,
              "servername": sn,
              "message": msg
            }
          })


def broadcast(message, room, connection, t):
  if t == 0:
    try:
      connection.send(message.encode())
    except:
      connection.close()
      remove(connection)
  elif t == 1:
    for client in list_of_clients.keys():      
        try:
          print("just send", message)
          client.send(message.encode())
        except:
          client.close()
          remove(client)
def clientthread(conn):
  while True:
    try:
      msg = json.loads(conn.recv(4096).decode())
      if msg["type"] == "sendmessage":
        res = send_message(msg["data"]["username"],msg["data"]["servername"],msg["data"]["message"],msg["type"])
        broadcast(res, msg["data"]["servername"], conn, 1)
      else:
        remove(conn)
    except Exception as e:
      conn.close()
      remove(conn)
      return

while True:
  conn, addr = server.accept()
  start_new_thread(clientthread, (conn,))

conn.close()
server.close()
#

Client code:

#Client

def game_lobby(sn):
  game_lobby_template(sn)
  while started != 1:
    msg = ""
    while msg == "":
      msg = input()
      if msg != "leave":
        send_message(sn, msg)
      else:
        leave_game(sn)
  start_game(sn, 1)


def receive_from_server():
  global server,members,data
  while True:
    res = ""
    res = json.loads((server.recv(4096)).decode())
    if res["type"] == "sendmessage":
      if res["status"] == 200:
        reload_template(res,0)
        else:
          reload_template(res,0)

receive_thread = threading.Thread(target=receive_from_server)
receive_thread.start()

#Suppose I call game_lobby() so that game_lobby is running at the same time receive_from_server is running

#

My problem is that the loop inside receive_from_server despite running only gets the first response from the server and then doesn't return anything despite receiving information 100%

#

Does anyone know why? Is this a multithread problem? A socket problem? I searched it up and there is a chance that I need to read the state of the sockets to understand if they can receive information? I do not fully understand the last one

hollow mirage
#

recv blocks until it receives data from the server or encounters an error

#

modify receive_from_server to use non building sockets and the select module

radiant vortex
#

Hi Guys!

#

I am working/starting a project that I desperately need help with.

#

I am using urllib to read a website which tells me all the movies that are on tv tomorrow

#

I have managed to obtain the HTML output, and at the bottom of the output after all the HTML code, it returns a sort of JSON dictionary which the Name of the movie, the title, TV channel & Rating.

#

Here is the code I am using:

from urllib.request import urlopen

link = "https://tv24.co.uk/movies/tomorrow"

f = urlopen(link)
myfile = f.read()
print(myfile)
errant bayBOT
#

Hey @radiant vortex!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.