#networks
1 messages ¡ Page 5 of 1
what protocol has that "messaging" concept?
well, in other words, what protocol(s) does irc use?
UDP maybe? but UDP doesn't guarantee all of the data will arrive (there's no concept of a connection, it's connection-less) and I've never worked with it. HTML is a request (ie. message) based protocol
No idea,
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
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
I see, I'll try out the method u sent above in a moment
<[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
one thing actually, this requires the other side to know how many bytes it'll be sending exactly because it'll send four bytes before sending the actual message
IIRC you said something was fragmented? can you determine how many bytes the whole message will be before sending it?
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)
Whoops, that should be data, I originally used blob everywhere but I switched to data since that's what your code calls that variable. I missed that reference, my bad!
all good
hmm but doesn't from_bytes return the first argument as integer
also I found a bit_length() method
yup, bytes_sent is the number of bytes sent by the other side, maybe it would've been better to call it message_length đ
oh wait hold on
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?
yeah
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
yeah
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
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
hmm ok, bytes_sent = int.from_bytes(s.recv(4), byteorder="big") I'm confused how this returns the length of the payload
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
yeah same here
the sender is responsible for first sending four bytes encoding the length (in bytes) of the message before sending the actual message
that's the s.send(message_length.to_bytes(4, byteorder="big")) line of code here in this example sender code
oh that's right
@open isle seems like it's still hanging
hmm, what's the code of the receiver and sender
hold on I think I did something wrong
oh thanks
hanging on input() or the recv() call?
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
hmm
conn.sendall(len(child.stdout.read().decode()).to_bytes(4))
?
hmm I can try that yeah
you should also probably save child.stdout.read().decode() into a separate variable just for readability
yeah, the first line of receive_data() needs to be response_len = int.from_bytes(sock.recv(4))
what's the difference between the two?
but then I turn that string into an int
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
ignore this
actually it makes more sense to do that
which way do you want do encode the length?
I switched it to from_bytes
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))
@open isle :white_check_mark: Your 3.11 eval job has completed with return code 0.
0005
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())
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 :)
huh
I'm going to copy and paste your code and run it locally
I probably missed something
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
yup, you got it
anyways, so are headers usually sent before the payload? Or are they usually combined into one datagram?
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
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'
doesn't the C-lang winsock library allow u to?
possibly i mean the socket library itself
since it's built around providing magic pipes from one end to another
!paste - hmm it seems to work on my end, could you share the full code of both the receiver and sender?
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.
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
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 đ
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
what was the issue, I'm still debugging đ
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
oh lol whoops
that was probably my fault actually
also it seems like using cd doesn't work when entering the command line
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
are you on windows, cd is a shell command on linux and the command is failing on my machine
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
cd seems to exist on Windows too
it does, but on Windows the code turns on shell mode automatically
I'mma turn that on always
lol bash ftw
yup
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
how is it not working?
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
cd won't work as expected because it only affects the current working directory of the subprocess call with ["cd", "somepath"]
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
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
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
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.
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
wow, you're right
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
I just removed the '\n' in the server and it hangs up the client
yeah because it's expecting one more byte
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
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!)
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++
Hello
i need help .
How can i receive data from server using irc lib?
@open isle think it would be better?
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
I've never used the irc library, but I recommend using an IRC chat client to talk with people on Libera, they're hella nerds on there
I want to write a script that automatise some task
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 ?
hmm not really, just gonna get started on the encryption
do u recommend anything easy to use?
lol of course, last time I touched that was 3 years ago
so not really. but the cryptography package on PyPI is quite nice (https://cryptography.io/en/latest/), its Fernat symmetric encryption seems easy to use
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
this is a #cybersecurity topic now, but it seems like assuming the implementation is bug-free, it's as strong as AES 128 CBC mode with padding per RFC 5652, section 6.3 https://github.com/fernet/spec/blob/master/Spec.md
we went from bash to processes to encryption
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)
@queen axle I made a document covering our custom message protocol. I also added some extra implementation notes, including a helper function to harden the implementation and really stamp out all of the different failure cases. https://docs.google.com/drawings/d/1U9EZ65kUHnDt4Qg2jIDQDfiCaXKxXtZd78n9cSg7wqQ/edit?usp=sharing
can vouch, additionally there's HMAC on top of it, so you also get data integrity for free
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?
hi i want to learn about servers any source?
What specific questions do you have?
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
ohk
i have a old android mobile i want to convert it into a server in which i can run my website / discord bot / script
seems like u did a lot of work on this
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?
Is this about hacking?
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
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
thx buddy
can i do something like use google drive for storage cuz my mobile dont have storage
At that point I think it would be easier to just host the stuff somewhere like https://render.com/, unless you insist on hosting the stuff on your own device
i dont want to invest money
There is a free tier to such services.
okay
hi, i want to know that does warp block open network captive portals.
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
accept() will block the code until a client connects, this means none of the sends or recvs will be ran until after a client connects (which makes sense)
if no client connects, the code will hang until a client connects
Wow okay that makes sense
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
...
you can't create an instance of a class before that class is defined
!e ```py
class Class:
xyz = Class()
@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
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()```
Thanks for the reply! I thought I had defined the class as "Network" on line 3, before I had created the instance of it on line 19 though? I am confident I'm missing something here..
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
like this
I do now, wow thank you so much for breaking that down!!
np
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?
hi, is there a way to figure out the optimal timing value to use for a timeout for some process?
guess and pray
using a wifi card in a virtual machine to use in monitor mode in made by Bridge Network?
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?
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
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 đ
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?
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()
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
does this this mean that it can't accept multiple clients concurrently? Like in the process of one client being thrown into its own thread, can it not accept clients during this time?
how does socket decide which clients to accept? In what situations could it obtain a client's ip and port but not be able to communicate with it?
not an expert here so dont take my word for it but it could be that the code is binding both the transmit and receive ports, which may not be compatible with Mac's networking stack
Yeah I agree. What would the point in binding to the transmit port?
well in simple terms it would allow a program to send data over a network using that socket using TCP or UDP
Why would you need to bind to it (tx)? Sample code for trivial udp client/server doesnât. I understand why rx does
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
All good bro
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 twosocket.socketobjects 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 whethergetsocknamerequires 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 theacceptmethod
thanks!
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?
Hello how can i build a sniffer using python
I know you can definitely send ICMP packets with scapy, it's just preparing, sending and receiving a response
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
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?
It's easier to work with HTTP requests using something like requests instead instead
!d requests
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.
OK, and how to listen to the data on IP:port using requests?
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.
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?
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!
im using ftputil, is there an easy way to enter a directory
i cant find anything about it đ
figured it out lol
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):
does anyone know how to enable monitor mode on windows 10?
do u have anything reapting over a socket when it dosnt have any operations left to do
can you include the bit after traceback
as in the traceback
could i say that a tree topology is a good example of network segmentation?/
scapy is one of the easier ways, or you can download nmaap
why do want one
def write_message(conn):
message = input(str('\n<<< (You): \n'))
if message == 'bye':
conn.close()
conn.send(message.encode())
perhaps not the source of that error but this will cause an error when you send "bye" because you close the connection and then try to send more data
try switching the order of the if statement and the last line
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?
I think you need to use the official gmail API
anyone use ciscoconfigparse and napalm? cant get both installed one breaks the other :/
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?
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
there are plenty of github libs that do this that yiu can get inspiration from
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)
hello
is there anyway to take two packets coming in on a socket and separate them into diffrent sections of a list
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?
Someone know how i do so its download a file to spesefic Path?
Hello everyone, before learning Django, are there any concepts or anything I should learn or know?
Good day guys, is there a library or way to do an ip rotation??
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
Why are you importing a queue and treading, this code looks dysfunctional
This doesn't resolve the public ip address
Itâs a very small portion of my script, when I get home Iâll send it all
Any recommendations on OpenSearch client libraries?
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
Donât do that, itâs scummy and unethical.
im using it for businesses purposes
Oh
im not dming random people
im using it so i dont have to copy and paste tell them
What does python -V tell you
fixed dw
@cloud spruce where are u
'''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
Threading is a terrible use case. for this, i would recommend multiplexing, such as select() or epoll()
Iâll try it in the future, threading was just the faster and easier route, im far more comfortable with threading than multiplexing
The way you're doing it Will never scan all the ports not even with 800+ threads the os can only handle like 500 threads per process effectively
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
Hi
Hi, I have a question. For SSL VPN do I have to use the vendor provided client?
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?
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
how do i make a webserver thats listening to port 2000 dm me to help
python -m http.server 2000 should work
no cause i use this hosting thing
It's kind of embarrassing that I can't find this myself...
Is RFC5321 (https://www.rfc-editor.org/rfc/rfc5321) the most recent specification of SMTP?
Are there other documents I need to read to understand how to implement a mail server?
Obsoletes: 2821
Updates: 1123
An RFC would have an "updated by" or "obsoleted by" header if it weren't the latest
as I understand, there's also some separate RFC for the actual email headers and such?
and for ESMTP extensions
đ¤ those are like twice as old as me
[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
arrrr why is it so complicated
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 :)
There may be a more accessible SMTP howto out there, although if you can read the RFC, it'll be the most correct resource
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
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. ;)
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?
anyone need networking help gotchu
I don't know the difference between OSPFv2 and v3 
Networking class be killing me
dm me
Nice! Though I was just joking đ
Glad to have you around here though
Maybe you can be the next rndpk
anyone know how to do this?
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
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?
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.
Hm. Cisco devices?
What are the different short formats it can be in?
Gi0/1
G0/1
G 0/1
That's all, right?
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.
@finite dock looks like it can really be any amount of starting letters
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
Hmmm đ¤
it autocompletes.. you ever press tab when typing?
haven't tried on packet tracer lol
it should i would guess..
btw.. consider gns3.. they gave it python support.
What is that?
another simulator like packet tracer.. only caveat is you need a real cisco image to build the routers
Ah, I see
We're using packet tracer in school so i'm just more familiar with that
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.
I'll keep it in mind đ Thanks for the suggestion
btw.. the labs you can vpn into, to test automation apps like ansible, genie, etc.
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?
Once you have sshfs installed, you can use the command sshfs [user@]host:remote_directory local_mount_point to mount the remote file system to a local mount point
Hello, does anyone know how to create a perceptron in python? help me please
What have you tried? @ember ledge
Hi
Hello there.
i am also intrested in this
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?
Generally I'll just look up the packet and Google will tell me the fields and what they mean
Do you know of any resource to properly learn about wireshark and real world application of it?
No, unfortunately đ
aight ty!
https://youtube.com/playlist?list=PLW8bTPfXNGdA_TprronpuNh7Ei8imYppX
https://youtube.com/playlist?list=PLW8bTPfXNGdAY3AfCNtm12Ogzryfs7Ket
awsome thanks!
you're welcome đ
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
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
how is that related to network @hidden mango ?
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?
can you configure it to allow outgoing connections but deny incoming ones?
that way your bot can establish a connection to discord servers
Doesn't work either.
I allowed all outgoing connections and denied every incoming except for the TCP connections with the discord IP's but the bot didn't respond
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?
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
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.
pls
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?
what's the project
it will take between 1 minute and forever
it is hard to argue with this assesment
@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
well, depending on other requirements, I would charge something between $200k to $5mil to do that
I'm sorry, I spent all my Millions on Fortnite
priorities
I suspect legal fees alone would be on the order of $200k for what HardTwerker described
anyone here good wit networking
What seems to be the problem?
Is there a fiddlerscript wrapper for Python?
thank goodniss you are here
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
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?
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.
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?
does anyone know how i can get the right TXT dns record?
Who is hosting your DNS records?
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?
Are you connecting to your public IP address instead of your computer's local one?
which part suggest that
What do you type in your browser's address bar?
my vercel app's url
Ah so you have a URL, are you certain that it points to your public IP address?
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
How are you connecting to the backend from the frontend?
im not, its just requesting the backend through axios
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.
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
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
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
show me the axios code that makes the request
also can you send a screenshot of how you've configured the port forwarding rule
we gotta go into dms for sharing sss
thats fine
dont trust 80k ppl with an ip addy
@pearl anchor this is the first thing I picked up on as well, I did read the question thanks đ
bro trying to help
was this the answer lol
Yeah lmao
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.
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?
They should not be able to see your photos and videos
Unless you transmit them over the network
Lmao what, it literally wasn't the right answer, unicorn is bound to local ip, whatchu mean that was the right answer
Did you try it in the end? Did it work? If not what happened
It wouldn't have worked with the local IP anyway so we fixed something
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
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?
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?
Byte in IPv4 and octet in IPv6
These days you don't need to "write" anything
I've self hosted my own VPNs before and they aren't too bad
I mean I have the VPS, I just need to use that server as a VPN protocol
Tho I prefer not to use a known protocol (WSTunnel etc) given how my country is very strict about detecting them
Yes, that's what I did
You won't need to "write" anything
Have you looked into OpenVPN?
OpenVPN gets frequently blocked here
That's attributed to the actual protocol being used
I don't believe openvpn is a protocol in and of itself
I meant when I use all the protocols it just doesn't work
not that the app itself gets blocked ofc
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
Well I'm hoping if I can use a TCP protocol and the server is unknown
maybe they won't notice
That's pretty much what openVPN does
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
SMTP is for mail transfer protocol
We're you thinking of SNMB?
not it was a protocol that apparently microsoft introduced
SSTP
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.
Can someone tell me how to use tcp ip
You're already using it now đ
How
You're on Discord, using the HTTPS protocol
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
The Hypertext Transfer Protocol (HTTP) is a stateless application-level
protocol for distributed, collaborative, hypertext information systems.
This document describes the overall architecture of HTTP, establishes common
terminology, and defines aspects of the protocol that are shared by all
versions. In this definition a...
It resides on the application layer of the TCP/IP model
What is an RFC?
An internet standard containing technical specification write ups by the Internet Engineering Task Force (IETF)
Technical specification details on many protocols are available as RFCs
Can somone help me depoly my api (in flask) online so other people can use it
choose hosting provider, package app, create deployment environment, deploy app, config environment, scale with whatever you deem necessary
after that just monitor your API
thank you you suffer any providers
why are you converting to bytes then back again
Not python, but look at all this freaking regex I had to build 
I have ascended into godhood
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)
can you post the error?
2023-02-06 15:14:55,295 - stream_consumer - ERROR - An error occurred while handling the websocket broadcast: object NoneType can't be used in 'await' expression
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
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
Broadcast: WebSocket events: HTTP events: URIs:
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??
A sign to use Rust 
Interesting, I will have to dig into how http and https work under the hood, and read more rfcs
Honestly it's not really all that interesting
Mostly just a layout for how text should be
Since I believe HTTP(s) works as socket under the hood
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
May someone help me
don't ask to ask, just ask the question
what do you mean exactly
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 !
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
already figured it out, but I meant that the websocket url would only use http protocol not ws
the issue was that I was typing localhost in websockets.serve
inputting a blank string worked
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.
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)
is there any way to host a website from a pc with only the ip address and not using any domain?
@frozen iris
Sure just port forward
yo how can you stream wave files through a socket connection with io.bytesio?
im kinda lost at that point
well where is there error
you cut out the line number when you posted the error
what have you tried
It was the line await websocket.broadcast(....
Its not an awaitable method
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
anyone know and want to explain to me why (working) proxies will refuse to connect/site will not send any data/other
fast file downloader:
https://github.com/skatbr/Python-stuff/blob/main/parallel_download.py
thanks
How is for example a youtube video transported over the internet? What protocol etc
Is getting a IT networking diploma a good idea
Probably just HTTPS
it's just a classic m3u8 video stream over https, like robin said
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
You can create your own Response object with that status code
import requests
response = requests.Response()
response.status_code = 500
Or you can whip up your own http server and send a request there
So like several https packets containing a few seconds of video data?
basically, most videos and live streams are just blocks of 30s video chunks which are then pieced back together
This is how HLS works which is what systems like Youtube, Twitch, etc... use
ah ty!
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
Could anyone explain why packet loss causes duplicate acknowledgements? Why would the client send multiple acknowledgements?
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?
use msgpack_numpy
https://github.com/e1pupper/VoiceChat here is something u can look into that will help you
i actually found a way with pickle but thank you for help anyway!
your*
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/
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)
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!
nice; amazing work
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
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
gm
with QUIC how do I install aioQUIC?
because I do pip3 install aioquic and it doesn't work?
can someone tell me whats the most important network-modules are?
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?
mee too
Hi guys, I'm trying to build a trading AI software, I need to speak with someone with good expertise in the field please.
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
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?
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"))
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
That's not really wrong. Pretty much what HTTP is
if your reponse is to me the app is a http server and its reading the clients postback in do_post of a HandleRequests(BaseHTTPRequestHandler):
Is cgi a necessary part of your app?
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?
Doubt you can do all that much about it
Why am I getting latency even to begin with?
Why would you not?
Everything has latency
Medium, processing time, host computational power
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
only to read the form value when its posted back, i dont know how to do it otherwise, that's what I need help with I cant find any examples showing how to do it without the cgi library
low spec device that is working its arse off to capture and encode the video buffer maybe? id be looking at load on the encoder/sender side, also cpu encode always takes more time vs hw encode like nvenc
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
FWIW I had terrible latency and quality on steam play myself too
Did u figure it out and fix it?
How to check if packets with UDP was sent in correct order with socket programming? How do I do that in python?
You can read POST request data like this
from urllib.parse import parse_qs
# in your do_POST:
content_length = int(self.headers.get("Content-Length")) # gets the length of the POST request body
query_string = self.rfile.read(content_length)
data = parse_qs(query_string.decode())
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>
"Send back their description" do the hosts on this IP have a special application ready to send back these "descriptions"?
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
so maybe?
I don't believe Minecraft servers use the traditional ICMP protocol
There are APIs out there that will do this for you
oh my gosh thank you so much
will this work with a whole list?
so is there a way to do it with icmp?
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
Minecraft does not use ICMP
when i try to ping in terminal it says icmp open socket operation not permitted... ugh
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
how did you even get that lol
You just type <@&267630620367257601>
<@&267630620367257601>
i was about to ping the admins and then i realized that would actually ping them lol
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
typing what
i just used <&role_id>
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.
Is python actually any good for networking
sure, why not?
Itâs more of a data science/machine learning language no?
@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
It's a GPL
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
https://requests.readthedocs.io/en/latest/user/advanced/#session-objects Referring to this one
Can you send your code?
Why not just write a ping sweep tool?, unless Iâve misinterpreted this and your just looking to ping already known ips
Use small tcp packets
I fixed THAT issue and ran into another wall...
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 = {}
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
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
And instead of using vActiveSession you should be using the session paramter of the function
but im calling that outside of the function
I know, but in your function definition you're using vActiveSession and not the session paramter of the function
You have r = vActiveSession.post(...
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?
!d logging
Source code: Lib/logging/__init__.py...
nice....
This is the documentation https://docs.python.org/3/library/logging.html
Can anyone help me to write program for idle scannig, together on github?
can you brief more, please?
I can't manage to upload a file to colabcode fastapi
I'll pay 30$ to whoever helps me in private
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.
sorry wait let me get this
!rule 9
malicious?
No, my bad
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
scan the open 'target' ports with 'zombie' device...
Itâs a dumb rule to make malicious projects illegal? đ¤
!rule 5 speaking of malicious projectsâŚ
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Correct me if Iâm wrong but isnât that the cloudflare dns?
the other one. it's not a malicious project
Technically this is only possible on the local network so, is not a malicious project
Port scanning can be used to identify vulnerabilities in public networks as well
@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
When I run this command:
wget --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://yahoo.com
...I get this result (with nothing else in the fil...
Thank you! I'll look into that :)
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?
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
Port scanning on public networks, IE McDonaldâs wifi is not illegal, what is illegal is port scanning on a private network such as a Network for company which is intended to be used by employees only
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
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
do you happen to have a source for that? I just haven't ever heard of such a thing
Yes
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
It says by technicality it is a breach of the law
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.
where are you seeing that?
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.â
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
interesting, didn't see that part
looks like it has never been enforced for port scanning though
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
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
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
Tested it out
Created 100 clients as subprocess under screen
if sleep == 0
other than that if sleep is every 10s its working fine
while trying to create a script to ssh into every switch on my network, I get an IO error. any ideas?
Anyone knows a method to receive data from clients constantly in socket? Without while
Don't think it would be possible without a while, if you want a non blocking loop then you use a asynchronous socket
Currently when I return a video file with fastAPI it is unseekable in the browser how do I fix that?
.
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?
nvm i got it
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
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
does anyone know how to send data to websocket
!pypi websocket-client @ember ledge
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.
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"]
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)
Should I have posted this question here? : https://discord.com/channels/267624335836053506/1035199133436354600/threads/1083092327616237571
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
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.
Exscript is failing to import hard, and I can't seem to find a good tutorial for telnetlib3
Anyone knows a library for creating servers?
a server in terms of what?
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
Yeah you can use discord.py to create discord servers
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
đż networking, change my mind
@polar sky What are we looing at here?
Looks like spanning-tree LOL it warms my heart
what data structure did you use
spanning tree protocol my beloved
Wouldn't it more sense to make a class called Tree
and instead of having an array that has 5 elements, you have a class, that has 5 attributes
So you could write your code like this
tree.mx = value
tree.child = value
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]
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
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
some trouble in #1084158859205161021
i think you're very confused as to how clients work
are you instantiating an AudioRC_Client instance and a AudioRC_Remote instance?
to handle server side of each, remotes, and clients
Hey @loud monolith!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
https://paste.pythondiscord.com/zuburolunu
everything after sys.exit() (Line 302) is the old server which is not modular - the reason I am here is to make the code modular, ordered within classes
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
what can I do then?
Are there any libraries for connecting and working with openthread APIs?
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.
hello, How can I publicly host my socket over my public address?
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?
You will have to port forward
But be warned because port forwarding can be dangerous
I have, but people cant connect
Did you give them your private IP?
I am first trying it on myself with my public IP
but it doesn't work
https://www.yougetsignal.com/tools/open-ports/ says the port is closed
The port forwarding tester is a utility used to identify your external IP address and detect open ports on your connection. This tool is useful for finding out if your port forwarding is setup correctly or if your server applications are being blocked by a firewall.
which I already have opened in my windows firewall
Which port?
that won't be necessary. I trust you know the difference between public and private IPs
I do
8466 is the same port the socket is listening on?
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
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
so for IP i do local host?
Try 0.0.0.0
sec
Thanks a lot! its working!
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.
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 ?
Do you mean a unix domain socket with "local socket"? They can handle multiple connections at the same time
@toxic mural in my case it can be either a named pipe (on windows) or a domain socket.
oh sorry, i have no knowledge about windows named pipes .(
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.
Wire shark has an OSPF display filter
Wire shark able to display a network packet and with the middle showing 5/7 osi model. Am I correct?
can someone help me with my multiplayer game thing. its pretty complex but h e l p #1086327929337819167 message
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
@remote citrus it's in italian Indirizzo = address
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 
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
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
Yep, as this says, the range is about limiting who can access your forwarding
Okay, so I think I know
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
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
Depends on how PATH is set and how executable is named. E.g. If you connect to Windows, you use its own names, so py
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!
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.
How can i send data through wifi using UDP in Python ?
hey guys how can click button on website using requests moduke... pls help
The requests module can only request web pages, so if your button leads to some other page, requests might be worth it, but if you want to press the button for some action to occur, requests is not useful. you should look into selenium
Has anyone ever tried to setup a small webserver in python that uses the QUIC protocol?
Just for simulation, not for real use
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
can I try and catch this exception using
try:
...
except TimeoutError:
pass
or it should be a different exception?
hey hello
weird question but
is anyone here able to help with entity relationship diagrams?
if the connection times out how would you keep it?
I should be able to reconnect no?
yeah, but you can't really "keep" it in that sense. sure, TimeoutError is the exception to catch
oh really
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
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
import requests
data = {'foo':'bar'}
url = 'https://foo.com/bar'
r = requests.post(url, data=data)
If the URL uses a self signed certificate, this fails with
requests.exceptions.SSLError: [Errno...
The server I'm sending requests to is not mine. I tried use verify="cert.pem", but it doesn't work
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?
same error
are you sure that the line of code raising the error is the line where you're passing verify=?
Yes
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?
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://.....
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?
can anyone here teach me websokets library i ant to master the library
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
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
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
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?
not clicking that đ
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
the "client" said they are experiencing bandwith issues
Look for lots of the same packets
It say singular malicious traffic though that canât cause bandwidth issues
Smells bad lmao
It's from the Internet Engineering Task Force, quite reliable and safe
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
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
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
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
This is the website: https://tv24.co.uk/movies/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)
