if you look at all the networks on the map you'll see that you have (in numeric order):
192.168.2.0/27 taking up 192.168.2.0 - 192.168.2.31 connected to eth1 on R01
192.168.2.32/27 taking up 192.168.2.32 - 192.168.2.63 connected to eth1 on R02
192.168.2.64/26 taking up 192.168.2.64 - 192.168.2.127 connected to eth3 on R03
192.168.2.128/26 taking up 192.168.2.128 - 192.168.2.191 connected to eth2 on R03
192.168.2.192/26 which would take up 192.168.2.192 - 192.168.2.255 doesn't look like it's being used and would then be free address space, this could be network A
192.168.3.0/25 taking up 192.168.3.0 - 192.168.3.127 connected to eth0 on R05
192.168.3.128/25taking up 192.168.3.128 - 192.168.3.255 connected to eth0 on R06
and everything fits neatly in a 192.168.2.0/23 prefix with would mean 192.168.2.0 - 192.168.3.255
#networks
1 messages · Page 45 of 1
it wouldn't be 10.0.0.22/30 as a prefix address there as prefix addresses should generally have the base network address written out not any other ip address contained within the prefix
and as image says that the interface address of eth0 on R01 is 10.0.0.21 (which can be annotated as 10.0.0.21/30 if one wants to include the prefix length with the interface address, but you wouldn't write it like that if it's a network prefix) and your instructions says that the link networks should all be /30 it must be 10.0.0.20/30 which includes 10.0.0.20 - 10.0.0.23 where the first address is the network address and the last is the broadcast address, this leaves us with two usable host addresses on that network 10.0.0.21 and 10.0.0.22
Very true. That case is clear! These make sense as they appear on the image. The ones that have to be guessed are harder for me to imagine
There's this other case. I get the 192.168.2 but not the rest, the .0/24
Specially the mask part /24, how come that /24 is the one and not /23 or /25?
R04 has all of the addresses on 192.168.2.0/24 reachable through eth0 as they are all on that side of that router
so they are all summarized in to one prefix pointing to the next router in the chain that can find more specific routes to the different longer matching prefixes contained within it
That's clever
and using 192.168.2.0/24 is the maximum length?
And the last question, if that's not right, but /26, why not use a smaller mask?
where is that, which router?
yes, /24 is the maximum length that would encompass all those networks
R04
I see it now, thank you!
any more questions on this or anything else related?
otherwise i'll just wish you all the best on the exam
Not regarding that imagine. Just that thing on R04
Though if you don't have time that's okay, you already helped me a lot
i got some time, just need to go afk for a little while, i'll be back in a short while
in the meantime just explain what it is about R04 that you have question around and we'll see if we can't work that out as well
also remember that a route entry point to the ip address (typically over a small link network) of another routing devices unless the network is directly connected to the routing device that has the routing table
Oh wait it does makes sense that is wrong! I see that the IP I uses there should have been the one of the router network
What I forgot about the previous attempt was is the difference of R01 eth1 and R01 eth2, why on eth1 the ip network is used and not in eth2, I don't the the difference on why these are different, specially since the IP of A is nowhere used either
That's the only remaining doubt now
i'm back now
i don't see how this image could be from R04 as eth2 is not on a directly connected network (not counting the link network)
in fact R04 doesn't have any directly connected networks other then link networks
eth1 and eth2 on R01 are just the same, no difference at all
they just want you to figure out for your self what the prefix of the network that they have only named A should be and they also gave you a clue that it's something within the 192.168.2.0/24 summarization (sometimes also called a supernet)
in #networks message i gave you clues how you would go about finding out which network A would be by the process of deduction and elimination, by excluding all other possibilities as they where already in use and finding the unused address space that is not used anywhere else in the network within the bounds of the address space that is otherwise used for the network
Ohh so what they give is not A's address!
Now I do get it!
they want you to figure out what prefix should go there instead of the placeholder A, in this case 192.168.2.192/26 as that was the gaping hole in the address plan after we had listed all other addresses used in the address plan for this whole network
haha, defensively not me because of #cybersecurity and running other peoples code like that 😆
@cloud spruce is it possible to do group chat in p2p?
like I've a setup wherein one client can wait for another client to connect to it and then they both can chat
it's just a one on one chat
I was wondering if it's really possible to do group chat
I can't think of a way
I have an old phone. Any projects I could do with it? Any ideas?
it's possible, but then every client must connect to every other client in the group and send the same message to everyone that should receive it in the group, at least if you want it to be truly p2p and not let clients relay messages to each other
is it possible to do sock.connect() multiple times?
I never knew that
you can, but you need to store all the sockets in a list of something like that and then check all the sockets for data using something like select() or other interface that might be better on the platform you are targeting (select() works good on linux, bsd, macos and other *nix like platforms, but it's not the best for windows even if it will mostly works there too)
or you might want too look into using asyncio instead which might be a better option for you even if it's more advanced to use
!rule 9 probably applies here
so you think a noob like me can grab your public ip and do very bad things with it and destroy your pc
dude, I learned to print("Hello, World!") like 4 days ago
someone that wants to do bad things can play what ever role they think will serve them best to achieve there goals, playing a noob, it-support, person with some kind of authority or what ever
social engineering is the oldest trick in the book and probably the most successful one too 😉
also, if you trick someone into running bad code on their computer you don't even need to know the public ip address to their computer to screw it up, and getting their public ip address and even a reverse tunnel into that persons computer would also be trivial in such a situation
that's why i won't run code from someone i "meet" that they wants me to run/try without first studying and understanding the source code, that's also my recommendation to everyone else if they ant to stay safe online
someone deleted my message...?
nvm I'll ask again
Say I've a list of lists of some ips and ports
[ [ip1,port,1], [ip2,port2], ...]
How would I go on to broadcast a message to all of them?
see too it that you have sockets connected to each peer, you can store the sockets in another list or other data structure, then you loop through the list of sockets and send the message to each peer
you probably want to be able to receive from all of those sockets too
yeah
makes sense
thanks
Only thing a public IP is really good for is rough geographical location, and also the ability to take you offline by DoS attack
But like mentioned a threat actor can use whatever method they feel is best to exploit you
my social skills is 0 anyways
time to take revenge from crush?
I wouldn’t
Don’t know how legal it is in different places
Also routers and ISPs have become pretty good at filtering obvious DoS traffic out
@civic dagger if your target has some interesting NAT configurations and ports open you might be able to get into a network and hack it from there
though most of the time you won't see a telnet port forwarding rule in the wild so it's not that easy
how do I make changes in resolv.conf permanent on ubuntu 22.04 ?
I tried like this
by changing in the head file located in /etc/resolvconf/resolv.conf.d/head but it didn't apply changes when I restarted the vm
U have to use a framework
Something resolv-framework
i wanna make a proxy, how do i view all outgoing requests from my local computer?
Does anyone has a good solution how I can connect to 2 Socket Servers at the same time with SocketIO maybe with different asyncio tasks ?
I have a gunicorn which I am running on Pycharm, but I cannot get the logging.info() to print out to the pycharm console (not working on Terminal too). I added those extra flags backend.gunicorn:application --log-level debug --capture-output --access-logfile - --error-logfile - (this is the whole script), but still it refuses to print out stuff
However, print("sstatement") prints to the console though.
you know how many public wifi's have a click to accept page and you connect to the internet? what if i wanted to make one of those for myself? how would i go about doing that/what do i google?
i wanted to send a list from client to server by services in ros, and faced a problem A file is auto generated by ros, and the file has a problem by default and gives me this error:struct error: the required argument is not a float.
this is the line whcih has error: buff.write(_get_struct_2f().pack(_x.coef_list, _x.bounds))
Are you referring to https://en.wikipedia.org/wiki/Captive_portal ?
does a switch need to have a static ip ?
in a TCP connection they have the data packets of; ethernet frame, IP datagram, TCP protocol. But what about a UDP conection does it have only ethernet frame, IP datagram only?
Hey all, just to touch base. im unsure if this is the right room for tools for CTF. Im trying to write a bruteforce login creds, how to I make sure that my socket connection is connected to the web domain im trying to brute force? If anyone could give me some tips or someone has already made on would be good 🙂 to see how you guys and gals did it
a switch don't need an ip address to do [L2] switching
if it's a managed switch you can will need an ip address on it to reach it if you are going to manage it over the network and not just via the a serial console or similar, but that ip address can live on another network such as an out of band management network
if the switch is a L3 switch and can do [L3] routing as well as [L2] switching it's essentially a router as well and will need at least an ip address on each network that it should be able to route traffic to and from
UDP is at the same level as TCP, so you'll find both an ethernet header and then an ip header in front of the UDP header
!rule 5 applies as we can not be sure that you are going to use such code only for authorized CTF comps
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Oh okay
we would probably need to see at least the relevant bits of your code to be able to help you with that
aha, you can't be sure the client will send the whole username or password in one single packet
so you can't just do one read and then move on, you need to loop for each response that you are expecting and search for a line break of some kind in the string before you move on
i would suggest making that a function for you too call each time you need to read a line from the socket
also, if you have it like you do right now with the accept() in one client connecting will prohibit any other clients connecting while it's processing that client
you essentially can only serve one client at a time that will block any further clients from connecting to the server
it's not bits, it's 1024 bytes and it will not wait for that many bytes
and it's not how recv() works, it will return up to 1024 bytes but it may also return just one bytes
in other words, you still need to loop and wait for a line break character of some kind before moving on in the code
yeah, the telnet client probably has remote echo turned on, so it will send each character to the server as it's being typed not waiting for a line break, and recv() will return that data as soon as it receives it
no problem
i hope you know that telnet and other such unencrypted protocols aren't secure and whom ever can intercept the traffic will see everything that is transmitted between the two peers
as long as you are aware and don't use it for anything "real" and more for learning, otherwise you probably want to wrap it in TLS or something (but then a telnet client will not be compatible with your service)
because even if it's not used for something important people unfortunately tend to reuse passwords which could jeopardize accounts on other services they use if the password would leak over this service
then the next stop on your learning path might be pythons ssl library to handle TLS: https://docs.python.org/3/library/ssl.html 😉
an advanced topic might be asyncio later on instead of threads for io bound workloads, applicable to most network related programs
there is #async-and-concurrency for that later on, but you may want to read up on the basics with a tutorial like https://realpython.com/async-io-python/ to get you started first
Hey! I just got an hoster and when i wanted to start it it said this: See screenshot
In short; It couldnt ping...
How can i fix this?
that library is using raw sockets which means that you need to either run it as root or another account that has been delegated CAP_NET_RAW permissions to create raw sockets
heyy, is there something like the socket module but online ?
Yeah, the socket module
Wdym by but online, it is online.
You need to port forward then.
so is there anything else
No, just redirect the designated traffic to the machine hosting the server via port forwarding.
are bssid and mac addr of a router the same thing?
Could anyone help me with GNS3 please, I have this lab screenshot I need to replicate.
i really do not know how though
how do I send files or folders from sockets?
maybe this might help ? https://www.thepythoncode.com/article/send-receive-files-using-sockets-python
!pypi pysendfile also might be worth looking into
Hello fellow programmers. I'm working on a project with a simple HTML form that uploads a file, like so:
<HTML>
<BODY>
<form action="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="upload" name="upload">
<input type="submit" value="Upload">
</form>
</BODY>
</HTML>
I want to emulate this with aiohttp, but I can't figure out how it's supposed to work.
https://docs.aiohttp.org/en/stable/multipart.html
This should be the multipart documentation, but it looks really complex for what I need.
async def accept_upload(self, req):
with open(_TMPFILE_NAME, "wb") as f:
post = await req.post()
f.write(post.get("upload").file.read())
self._job_handler.queue(_TMPFILE_NAME)
return web.Response(status=200)
The upload endpoints looks like this, and doesn't require this fancy-schmancy multipart reader stuff. I ought to be able to write in a similar, simple fashion.
Anyone know what's going on and how I can fix it?
Looks like accepting the upload doesn't work quite right either, because post.get("upload") returns a bytearray object.
So I don't exactly have no idea what I'm doing... but I have no idea what I'm doing. 😂
I'm quite lost here despite having nice documentation. 😂
The code for the upload endpoint was partly copied from some part of the official aiohttp tutorial IIRC, with modifications that I made probably.
So, uh, as usually happens when I post a question here, I've fixed it. 😐
So I'll change this from a "help IDK what I'm doing" to a "I did something but did I do it well?" question
async def test_server_writes_request_body_to_file():
mock_handler = Mock()
app = init_app(mock_handler)
async with TestClient(TestServer(app)) as client:
with aiohttp.MultipartWriter("form-data") as mpwriter:
mpwriter.append(io.BytesIO(b"yay"), {"name" : "upload", aiohttp.hdrs.CONTENT_TYPE : "application/octet-stream"})
await client.post("/upload", data=mpwriter)
_, args, _ = mock_handler.mock_calls[0]
with open(args[0], "rb") as f:
assert f.read() == b"yay"
Got my test.
async def accept_upload(self, req):
print(req.content_type)
reader = await req.multipart()
filedata = await (await reader.next()).read()
with open(_TMPFILE_NAME, "wb") as f:
f.write(filedata)
self._job_handler.queue(_TMPFILE_NAME)
return web.Response(status=200)
And my handler.
HTML form is unchanged.
i don't really understand if you aim to implement the server side stuff, the client or both using aiohttp
and if you are implementing a simple client async programming might be overkill here
My collaborator is familiar with aiohttp so I believe that's why we're using it. The client is currently just the HTML form, and later it will be JavaScript probably, to run in a web browser.
what should be the number after the / for a range of 190 starting at 172.16.0.10/?
Hi do you require IP address range to start from 172.16.0.10 and end in 172.16.0.190 ? Is it not possible to start the subnet from 172.16.0.0/24? then you have more 252 usable IP address/hosts ( 3 IP address reserved network, gateway and broadcast address)
it's not even possible to have a network like that, that's just an ip range, you will be required to take up the whole range from 172.16.0.0 - 172.16.0255 to accommodate that range of addresses, where .0 and .255 can not be assigned to any device
the network will then be 172.16.0.0/24 as @brisk orchid said
!pack websockets ?
ty
Hiya folks,
If I know my friend’s IP, I can connect to his server which he’ll be running when using sockets, right?
Is there any limit to such action? (For example distance / anything else)?
Nope, it'll only not work if he doesn't have it port forwarded
it must be a public ip address, not a private ip address that is just available on your friends network
if your friend want to run the socket server on a computer on a private ip address they must first configure their router/firewall to port forward traffic from the public ip address on that device to the machine running the socket server
if there is a firewall in the path (or on the machine) it can stop the connection unless configured to allow that traffic through
Thanks peeps 👍
Hey! I'm trying to make a chat server. I need multiple users connected simultaneusly so i've been looking into threading each client. Problem is when i call socket.recv(16) on the client, i get error the following error:
OSError: [WinError 10038] An operation was attempted on something that is not a socket
Can anyone help?
import socket
import threading
PORT = 13031
class ClientThread(threading.Thread):
def __init__(self, socket, addr):
threading.Thread.__init__(self)
self.socket = socket
self.addr = addr
print("New connection added: " + str(addr))
def run(self):
print("Connection from: " + str(addr))
while(True):
print(self.socket)
msg = self.socket.recv(16) # Error 10038 on client connect
print(msg)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
serverAddr = ('localhost', PORT)
print('starting up on %s port %s' % serverAddr)
sock.bind(serverAddr)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print('waiting for a connection')
conn, addr = sock.accept()
try:
newClient = ClientThread(conn, addr)
newClient.start()
finally:
conn.close()```
the call to conn.close() within the finally block will run in the main thread before you even have a chance to do the .recv() on the socket in the client thread, this is what is cause that problem
16 bytes is a bit small for a .recv(), consider using at least 1472 bytes or more to be able to gobble up the payload of one full tcp/ip packet on a standard network
i would suggest using asyncio instead of threads in such use cases if you need to scale the solution to many clients
but it will involve more new concepts to wrap your head around working with async/await if you haven't done that before
there is however the channel #async-and-concurrency for such things (including threading if you want to stay with that but still need any help in that department)
@cloud spruce That's it! Thanks! I'll look into the asyncio thing.
I am aware the recv is short, i have more code to deal with message lengths, just omitted it because it wasn't important for this issue.
One more issue, one i was dealing with before switching to threads. When the server is waiting for .recv(); if the client disconnects abruptly, .recv() will throw an error and basically kill the server. Is there a better solution to this than wrapping it in try-except?
The error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host```
I am aware that the client can help perform a graceful disconnect, but i can't trust that it will happen every time
i would wrap either the read or the whole while loop if it doesn't contain to much code in a try-except and only catch the specific exception in the except that i expect could happen within that block and that i want to catch on that level
@cloud sprucealright, thanks again! I did some reading about asyncio and i can see why it's preferable.
now we are venturing a bit off-topic for this channel and into the land of #async-and-concurrency
if you are going to write for example an async network application you should use async libraries for all io where the application could be waiting for something such as file system access or database calls that isn't cpu bound
hey
how are you
i
am
fine
thx
just tring to hit
50
msg
so i
can
chat
!rule 7 and don't spam a channel
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
فك اوف
Why does only 1 client connect and not 2?
Server:
#new code
from re import T
import socket
import threading
import time
clients = set()
clients_lock = threading.Lock()
HOST = '127.0.0.1'
PORT = 9090
def acceptclient():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
con,addr=s.accept()
print(f"Connected to {addr} adress.")
con.send("You are now connected to the server.".encode("utf-8"))
with clients_lock:
clients.add(con)
try:
while True:
data = con.recv(1024)
if not data:
break
else:
#print(data.decode("utf-8"))
with clients_lock:
for c in clients.copy():
c.sendall(data)
#con.close()
#clients.remove(con)
finally:
print(f"Disconnected {con}.")
while True:
acceptclient()
Client:
import socket
import time
HOST = '127.0.0.1'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
data = s.recv(1024)
if not data: break
data = data.decode('utf-8')
print(f'{data}')
time.sleep(1)
inputs = input("Your Message:")
s.send(inputs.encode("utf-8"))
because you're not doing threading, asyncio or any other type of concurrency or non-blocking io in your server code as far as i can see, which means it's busy in blocking calls waiting for data from the single client and can't do anything else
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
Y'all I need some help. I am a coach for a robotics team at a school and we need to setup a network. We can't use the schools network because it is so locked down. We can run our network just fine but when we plug our router into the Ethernet of the school, the schools admin gets in a pissy fit because he gets a notification there is a rouge DHCP server. Which is technically true but no devices outside of our network ever connect to our router and we aren't trying to man in the middle our own devices... It's also on Saturday so it's not like anyone else is trying to use the network anyways
What am I supposed to say to him lol
He's also IT support for a high school with a "degree in windows and worked in geek squad for 10 years" so there's that
Is there a way to print stuff when input is active? (by input i mean Input = input("Your message: "))
Server:
import socket
import os
from _thread import *
import threading
clients = set()
clients_lock = threading.Lock()
ServerSideSocket = socket.socket()
host = '127.0.0.1'
port = 2004
ThreadCount = 0
try:
ServerSideSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Socket is listening..')
ServerSideSocket.listen(5)
def multi_threaded_client(connection):
connection.send(str.encode('Server is working:'))
with clients_lock:
clients.add(connection)
while True:
data = connection.recv(1024)
if not data:
break
with clients_lock:
for c in clients.copy():
#print(c)
c.sendall(data)
print("SENT")
while True:
Client, address = ServerSideSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(multi_threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSideSocket.close()
Client:
import socket
ClientMultiSocket = socket.socket()
host = '127.0.0.1'
port = 2004
print('Waiting for connection response')
try:
ClientMultiSocket.connect((host, port))
except socket.error as e:
print(str(e))
res = ClientMultiSocket.recv(1024)
while True:
Input = input('Message: ')
ClientMultiSocket.send(str.encode(Input))
res = ClientMultiSocket.recv(1024)
print(res.decode('utf-8'))
ClientMultiSocket.close()
Multiple connection is managed by server.
input() is a blocking call and you're not using any kind of concurrency (asyncio, threads or multi-process) so your program can't do anything else while waiting for the input to finish
even if it did it would probably get messy as you are only using stdin and stdout in a terminal kind of environment
what would happen if the user of the client is in the middle of a sentence or a word when data comes in from the server and immediately gets printed where the cursor is currently positioned?
to fix that you would need something like a gui or ncursors if you stick to a terminal and some kind of event loop
the router should typically not have the DHCP server running on its outside interface connected to the upstream network and everything should be fine
or if you have connected the router to the network using one of the switched ports its only acting as a switch and you should simply be able to turn off the DHCP server in your router and the clints on your router should get their ip addresses from the schools DHCP server instead
if the school network has proper network equipment that was properly configured this wouldn't be an issue at all since it would guard against a rouge DHCP server from even being able to affect the network at all using something like DHCP snooping, but at least they have some kind of alert warning them about it, so that's at least something, feels like it's just half way implemented though
a rouge DHCP server can have lingering consequences for devices on the network even after it has been disconnected from the network and make the affected devices use the wrong ip space which would make them unable to talk to anything else on the network that isn't adversely affected in the same way, especially not being able to talk to the gateway and connect to anything outside of the local subnet, and how long those problems last will be determined by the lease timers controlled by the rouge DHCP server or until the device is rebooted after the rouge DHCP server is off the network again
Hi,
I'm looking for feedback on https://pypi.org/project/cidr-bottle/ and https://pypi.org/project/cidr-man/:
- Any features you think are missing
- Code review
- Criticisms?
Thanks,
Tim.
Thanks I appreciate your response. We can't use the switching option because they have stupid thick security so we can't ssh or set device side static ips. It's also not running outside it's interface and we have never gotten a rogue device connected to the router verified by logs. We connected it to the schools router by the wan port which shouldnt be switched but I can check the router page.
And no, this guy is a high school IT support. The network isnt properly configured. He told us if we didn't stop he would "stop us" but by "stop us" he meant he would just disable all the Ethernet ports for good
Also our lease timers are 10 minutes and we're not trying to DHCP snoop either so there's that
you are using a normal home router and connecting its wan interface to the school's network, right?
i meant the wan interface when I said outside interface, it's really strange that your router is acting as a DHCP server on the wan interface, that is very unusual and you should try to turn the DHCP server off from that interface if it's really on, usually the wan interface of a home router would instead act as a DHCP client and ask the network for an ip address to use
you shouldn't need to set any static ip addresses or do you require them to be static for your project?
if you do need to use static ip addresses it should be fine behind the home router if you use NAT on the router just like it would be setup if you ran it at home between the internet and your home network
and what is this about ssh?
you shouldn't need ssh, and if you do need it for your project it should still work within the network you create behind the home router
it's good that you keep the lease timers low for now so that there is less risk of you inadvertently create a problem on the school network as their network doesn't seem to protect against that enough
no, DHCP snooping doesn't have anything to do with you sniffing or doing anything malicious (and i'm not saying/suggesting that you are)
DHCP snooping is the name of the security feature in many managed switches like the ones your school probably have, it configures the switch to detect DHCP traffic from non-authorized DHCP servers on the network and block that traffic so that they can't create a problem on the network in the first place
does someone have a python script that will proxy all traffic that gets connected to it, to an appropriate endpoint (the endpoint the client tries to get to)? the smaller the better
Why specifically python? It's generally too slow for that kind of thing
because i cba including other languages, also the amount of network packets being sent is minimal in this case, so performance isn't a big issue
I had written a toy proxy that used Twisted to provide an MTLS termination for internal services at DeBeers. But I've not written a multi-protocol solution in python before.
Is it all HTTP? and TCP?
technically I'd only need to support TCP, although having support for both would be ideal. I started with just making HTTP support, but couldn't get it to work
I want to connect it up to my phone to MITM certain things, and ideally I wouldn't break everything else whilst doing so
So raw TCP should be fairly simple and support http too, so long as you don't want it to intercept HTTPS or TLS
If you want to handle encrypted traffic then you need to look at protocols like SOCKS... but this doesn't really give you a lot of access to any of the data that passes through.
An alternative might be to use Burp Suite and then parse the stream feed
Burp Suite is a pretty complete solution, and gives a lot of access to the data that it proxies without significant effort
don't remember if it's using HTTPS, currently I'm using windivert to proxy to intercept and modify packets, but it's very slow and also effects the entire network flow on my PC and can slow down the network a lot.
As for Burp Suite, it looks like it would be over kill for my system at first glance. If I could get a basic HTTP protocol working I could probably figure out the rest of the hoops myself
looking for people that know hdml
I would suggest you look into Twisted then, it's a really mature python networking library
would really prefer not using a library, but I will check it out. Thanks
Twisted's documentation is a little shit, but it's the best option. Doing it in pure python from scratch is going to be a bit too heavy
Yeah will check it out, is it possible to see which 3rd party libraries it requires?
If you're still struggling on Monday, I could help when I'm streaming
Twisted doesn't have any external dependencies IIRC
if it doesn't then it should be fine 
looks like it adds a couple, but doesn't seem to be too many
will try to make a implementation tomorrow, thanks
ahh okay it's added a few since I last looked
zope.interface >= 4.4.2
constantly >= 15.1
incremental >= 21.3.0
Automat >= 0.8.0
hyperlink >= 17.1.1
attrs >= 19.2.0
typing_extensions >= 3.6.5
twisted-iocpsupport >= 1.0.2, <2; platform_system == "Windows"```
@rigid wing Sure, have a go with twisted I think you should be able to get it done pretty easily (although I admit the documentation sucks a little).
If you get stuck I'll be streaming on twitch (https://twitch.tv/plaintextnerds) on Monday from 10:30 (UTC+1 / BST), I'll be happy to answer any questions and help you debug / write it. I have an open-door policy on my stream so provided I'm not working on a client project you're welcome to ask for debugging and network coding help.
(He/Him) Tim is a Staff / Lead Engineer that specializes in networking and real-time technologies but has a growing passion for games and video streaming. Each month he spends 2 weeks working on GeoIP.Network, and the rest of the time Writing.
Feel free to drop in any-time and I'll be happy to help
The only exceptions are as I said, if I'm working on a client project, or already helping someone
Sounds good, thanks 
The API documentation link I posted earlier was not the one I intended, I meant to post this one: https://twistedmatrix.com/documents/current/api/moduleIndex.html
@rigid wing To get you started you basically need the Echo Server example from https://twistedmatrix.com/trac/ and this module https://twistedmatrix.com/documents/current/api/twisted.internet.tcp.html
There's a HTTP proxy example here: https://wiki.python.org/moin/Twisted-Examples
This one is a bit more manual (and old), but I'm fairly sure that it will still work: https://blog.laplante.io/2013/08/a-basic-man-in-the-middle-proxy-with-twisted/
I want an explanation about peer to peer. Specially why is it preferred at all (except maybe for direct messages)
multi-player games and chats usually go through a server and not directly between participants, this also maintains users relative anonymity and protects users against others finding out their public ip addresses which can give away information about a possible rough location amongst other things as well as open up possibilities to attack each other, mainly with different kind of DoS attacks
peer-to-peer mainly has a usage when there are very large data transfers that you don't want to burden the server with but comes with challenges when both parties are behind different NATs
you can often overcome those challenges using techniques such as STUN, ICE and TURN, often involving a third-party (not behind a NAT) to use for the initial information exchange needed between the two parties that is each situated behind different NATs that want to communicate with each other
https://en.wikipedia.org/wiki/STUN
https://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment
https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT
@ember ledge as @cloud spruce says P2P is not something commonly used in NetCode for games, it almost always goes via a gameserver. This is partly due to the pragmatic simplicity (vs trying to orchestrate p2p state consensus - See RAFT protocol for more info), but also because Eyeball Networks (home and office ISPs) tend to have shitty peering and transit management leading to asymmetry in latency, jitter, and packet loss.
It might be used for reducing the load on servers w.r.t DLC distribution, but in these situations it's little more than Bittorrent.
If you want to look into building a gameserver manually (rather than using something like proton), then you'll need a good grasp on UDP wire-protocols, Pub-Sub architectures, statistical analysis (for cheat detection), and UDP reflection attacks (or more specifically, how to prevent them).
Python is not an ideal language for any of these as you have a <5 msec response window per client update. That's not to say it's impossible, you can do it, but it's harder than it needs to be and you end up using CTypes, and a bunch of bit-wise operations.
A common language choice for this C# as it has high-performance built-in binary marshalling and un-marshalling. I've worked on C++ based game servers too which isn't too painful, provided that you can keep the protocol simple enough to use PODS (Plain-Old Data Structs), but if you start messing with the packing and/or Endiannes, then it can get messy.
Yeah we need ssh and static ips for our project. Which is why we can't just use the school network as they don't allow us to communicate between devices. We have our internal network setup how we need it and yeah we're using some random home router. That being said, I still don't know how it would be a rogue DHCP server when we have never had a connection by a device outside of the network...
I'm kinda at a loss for what to do... This guy also communicates through a student who runs track? and doesn't ever talk to the coaches directly and his solution if we don't "stop" is to just shut off the network on the weekends lmao
The conclusion that the coaches have come up with is that he is just trying to be self important and there's not an actual issue and it's nice to know that so far that is a correct assessment
okay, got it, then i see why you would need static ip addresses and ssh access within your own little network that you have created on the inside of the home router, and this setup should allow for that
the terminology "rogue DHCP server" just mean a DHCP server that shouldn't be on the network as they can negatively affect the network
it got nothing to do with anyone else connecting to the network from outside
as long as your home router is connected to the school network with the WAN interface and the router is setup as it typically is for home usage, where the router will act as a DHCP client (not a server) on the WAN side and just run the DHCP server only on the LAN side, you should be fine
just see to it that your home router is set up to act as a router/firewall and not a switch between the WAN and the LAN side and will apply source NAT to the traffic from the inside network which traverses the router to hide the inside ip addresses with its own ip address that it got from the school network
We need NAT and DHCP on our network, but we still don't have a resolution because we're doing all this stuff and he's still bitching. But then again he's also communicating through some random student without actually talking to us lmao so
My point to the outside devices thing was if our server was actually serving DHCP addresses, then other devices should be connecting to it right?
if it's setup as i think it is, it should just work, it's hard to trouble should like this over chat and not being able to see how things are really setup
I mean it works
It's just this guy complaining about it
We never have any technical problems especially because they use 10.0.0 and we use 192.168.1
if your home router was acting as a DHCP server on the WAN interface (which it shouldn't) and affecting other devices on the school network (which i really hope that it isn't, that would be bad, hopefully the switches on school network are properly setup with DHCP snooping to protect against that) they probably wouldn't find their way to your router because the ip addresses that it would give out would be for the LAN side (inside) of the home router which those devices wouldn't know how to reach and thous would not be able to even try to connect to your router
when are messages sent via tcp/ip broken up into packets? I looked at http://web.stanford.edu/class/msande91si/www-spr04/readings/week1/InternetWhitepaper.htm# and it says that each layer breaks messages into packets, whereas at https://www.bbc.co.uk/bitesize/guides/zj88jty/revision/7 and most other websites say that messages are split into packets at the transport layer.
Learn about and revise networks with this BBC Bitesize GCSE Computer Science Edexcel study guide.
A slightly technical whitepaper explaining what makes the Internet tick.
So the devices would just get stuck or would they connect to the proper schools router
that would be implementation specific to the os and in some cases even the drivers loaded in the os and used for the specific communications ,as sometimes much of the work is delegated to the NIC hardware offloading so that the cpu doesn't have to do so much processing
if the school network doesn't filter out the traffic properly and it would leak in to the school network the affected devices would just get stuck and not being able to talk to anything else then other devices that are stuck in the same way, not being able to reach any gateway or router to reach any other network, this is why it would be a bad situation for those devices
fortunately you said you have a short lease time, which means that as soon as your router is disconnected the devices that would have been affected would recover when the lease expires at the very latest
then they would request a new ip again and this time the schools real DHCP server would answer and they should get the correct information
do you mean when the message is broken up into packets at each layer or when it is at the transport layer?
at the application layer (layer 7), presentation layer (layer 6) and session layer (layer 5), it's just data
when the data enters the transport layer (layer 4) it gets turned into segments, datagrams and such depending on the protocol in use at this layer
then that is split into packets at the network layer (layer 3)
and packets are put into frames at the data link layer (layer 2)
I was taught in school and read on the internet that the TCP/IP protocol only has 4 layers. so, TCP/IP protocol has more than 4 layers? or is it just a small part for a certain layer?
the whole iso model has 7 layers, but TCP/IP stops at the 4:th layer (TCP belongs to layer 4 and IP belongs to layer 3), then there are usually other protocols on top of TCP making up the last 3 layers (layer 5 through 7)
many times this theoretical model is not really how it works in the real world and there isn't always such a clear cut way to separate what is going on on top of TCP into all of those layers other layers
okayyy, thanks for the explanation
here is a pretty dry explanation of it: https://en.wikipedia.org/wiki/OSI_model
When I send a set of bytes from a client to a server via socket, do those bytes also include the TCP/IP bytes, or strictly just whatever else I am wanting to send to the server?
I ask because I'm trying to measure the amount of total bandwidth used when sending an image. I tried using net_io_counters().bytes_recv from psutil but I don't think it's exclusive to just what is being sent over a socket
So even if we were serving DHCP addresses we would potentially disconnect random library computers for 10 minutes on a Saturday when nobody is there. But that makes sense thank you
yeah, so probably not the end of the world 😄
but there might be other systems on the network then just library computers, hopefully nothing too critical though as that should go on it's own network segment 🙂
I mean idk the network isn't really set up that well so
you'd need a raw socket on the client which will then receive the entire payload, but you'll need to parse out data length from the headers to receive the segments properly
but it's more than likely the header overhead is negligible to the actual payload, unless the connection is very unstable and has a lot of retransmission
When I send a set of bytes from a client to a server via socket, do those bytes also include the TCP/IP bytes, or strictly just whatever else I am wanting to send to the server?
The former of course. If you just threw your data how is it supposed to arrive anywhere with no headers?
I ask because I'm trying to measure the amount of total bandwidth used when sending an image.
The tcp/ip header is 40 bytes.
Even if you don't use packets efficiently and keep sending them out before an MSS worth of data is buffered, the overhead will be negligable, and pratically non-existant if they're used efficiently.
yes
!pypi pygame
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Why am I able to reach my webserver im hosting myself if im connected to the same wifi but not if im connecting from outside my wifi?
From outside your wifi, you mean from the internet?
on your wifi you use private ip addresses, these can not be reached from the internet where only public ip addresses are used
your home router asks your ISP (Internet Service Provider) for a public ip address to use for a while and get one of those ip addresses
the home router is also a firewall and does something called source NAT (Network Address Translation) and masks the private ip addresses so that it looks to the rest of the internet like the traffic is coming from the router/firewall
to be able to get connection from outside to a host on the inside you will have to login to your home router as an administrator and setup something called port forwarding
I don't suppose there is a standardised way to log in to my router as admin? Is it dependant on the manufacturer?
visit your default gateway
if your on windows, open CMD and type ipconfig and you'll see something like this (the ip might/will be different)
then type that ip into your browser and hopefully there will be a login page
does anyone know any free vm for m1 macs?
Do you know a good resource on how to configure the port forwarding?
Ghost ping 😶
Look at my messages
That will take you to your routers admin page
Yeah I managed to login to the configuration webpage but im not sure how to set it up securely and correctly
Do you see a port forwarding tab?
Yeah
that will be a bit different from make to make and product to product, what do you have?
strange setup, the router should know its own external/public ip address, so usually you don't have to put that in, here it looks like you will have too 😕
Isn't external host the device I want to be able to connect from the outside? And internal host is the device it should be forwarded to? And external port is the port it should take the data from and internal port is the port on the internal host?
But im just guessing
maybe, but usually when you do port forwarding you allow anything out on the internet to connect to it unless you add additional firewall rules to the router
so ot can also be your external/public ip address that should go there, which would be bad if it changes as they often do
I mean I am configuring this to make my webserver visible to everyone else so that wouldn't necessarily be bad?
no, not at all
what would be bad is if that field instead is used to fill in your public ip address since that would be a chore to keep up to date when ever it changes
Yeah that wouldn't make much sense though since the gateway isnt really considerd external? I always thought of it as on the network
the router must have an external and publicly routable ip address on the wan (outside) interface or this won't work
why isnt my server staying open?
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8820 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Is it connecting with the server.py?
does ip(public) tracking track all search results or searches on a browser?
basically had to click two different buttons for it to work... very strange
that code should work, but it will only handle one client and then quite when that client disconnects from the echo server
there is other improvements to be made as well, for example using context handlers
more context please, what ip tracking done by what or whom are you talking about?
Yep ip is how the internet communicates
google knows every website you visit based on DNS and google searches, they have a contract with many governments to report certain websites etc
as for browser specific tracking im not sure
yeah thanks guys🥰
your ISP and some government branches of the country where you are connected to the internet might be tracking connections, dns lookups and other data as well
nah not that serious it's just a casual site :p
that's not really the point, just assume "they" are logging everything they can from everyone, "just in case" they need it later or to run automated correlation on the data
yeah they prolly even do that but nothing i can really do abt it can i other than switching browser ig...
for google and other companies this is big business and the foundation of income for internet advertisement
some browser extensions and other software on your computer might do the same as the browser can and collect this data and send it to the cloud as well
i see ||so no privacy||
at least don't count on it, assume the worst and hope for the best 😉
mhm
Nope, not really in today's world
Anyone knows how I could make a program (on win10) go through a specific proxy
only that specific program
usually you configure that within that program
Doesnt have the option
can you use something like proxifier (look it up on google) for your application?
I'm trying to automate downloading a file. When I paste it into IE or Chrome it downloads fine - https://www.gunviolencearchive.org/export-finished/download?uuid=1e1fc646-a270-420e-8b41-3f497794831f&filename=public%3A//export-6bc2c6aa-4952-4b6a-9684-3ae29fb0c5cb.csv
When I use this code
req = requests.get(downloadurl, stream=True)
filename = req.url[downloadurl.rfind("/") + 1 :]
with open(filename, "wb") as f:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
It doesn't write the CSV file....instead it writes this file:
Hey @scenic jetty!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
looks like it's a page that contains javascript that your browser probably runs before the download process starts, but your script instead downloads the page with the javascript on it that would initiate that download
think i should use selenium instead?
I found proxycap
does it work for your use case?
Yes
either that or if you can work out what the real url is for the files you want that the javascript on that page fetches
you might start by bringing up the developer tools in your browser and check the network tab for which network resources it reaches out to
wasn't that the same url that you wrote from the beginning?
yeah but apparently it was detecting i was trying to scrape so this worked:
import pandas as pd
uri = "https://www.gunviolencearchive.org/export-finished/download?uuid=1e1fc646-a270-420e-8b41-3f497794831f&filename=public%3A//export-acc15238-e2b3-4fe9-82cb-75c537b8d621.csv"
opts = {'User-Agent': 'Mozilla/5.0'}
df = pd.read_csv(uri, opts)
and just using requests with a spoofed user-agent didn't work?
it might have
when i was researching i just found this way to directly download into a df
Oi pessoal!! Eu acabei de partilhar um tutorial no Youtube sobre como instalar o banco de dados MongoDB. Então peço ajuda da comunidade pra partilhar e ajudar outras pessoas que precisam saber disso. E desde já eu agradeço acessar lá meu canal curtir e subscrever o canal da colega aqui tentando ajudar outros que estão iniciando na área de dados. Beijosss
https://youtu.be/da5f7619TNA
MongoDB - Tutorial Instalação

O MongoDB é um banco de dados orientado a documentos que possui código aberto (open source) e foi projetado para armazenar uma grande escala de dados (Big Data), além de permitir que se trabalhe de forma eficiente com grandes volumes.
Como Instalar o MongoDB Community Server no MacOS (Apple M1 - Monterey)
...
!rule 4 english please
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
and i think #networks is probably not the right channel for mongodb related stuff
👍
How do i get the folder name from the remote machines using PARAMIKO
what have you tried so far, do you have any code?
still, have you tried anything and how does that code look?
def b():
for i in iter(_stdout1.readline,""):
tot_size = sum(list(map(int, re.findall('\d+', i))))
print(f"DATE {date} : {username} File size is {tot_size} kb")
remote=[f"/home/server2/Desktop/backupdestination/{year}/{month}/{date}/",f"/home/server3/Desktop/backupdestination/{year}/{month}/{date}/"]
code1 = f'local = "{remotes!r}"; import os,json,sys; json.dump([os.path.getsize(os.path.join(path, filename)) for path, dirs, files in os.walk(local)for filename in dirs],sys.stdout)'
_stdin1,_stdout1,_stderr1 = client.exec_command(f"python3 -c '{code1}'")
@cloud spruce
if I have a server and a client, how would I run both of them at the same time? pycharm limits to 1
the only thing that worked so far is running through both vsc and pycharm
one for clinet and one for server
and you don't want to just rely on the shell command du -sk * or similar?
you can run your python code in other ways then just from a ide
are you on windows or what platform are you on?
windwos
whenever I run it in CMD its just stopping instantly
and opens pycharm
How can i use du -sk please help me @cloud spruce
ANy one?
PyCharm must have created an association to files with the .py file extension
But you can have the two scripts open in the editor and run them in parallel
How?
The quickest way is to use PyCharm's intelligence to run scripts that have an
if __name__ == "__main__":
main() # main should be a function running the main logic of the program and is generally good practice
PyCharm should show a green play button to the left of the keyword if
Or next to that line somewhere close
So you can write this line for both scripts and define each their own main function and click the button shown by PyCharm
but the server needs to be open first
yes
Good
This is hardly a #networks question by the way, more for #editors-ides since we're discussing PyCharm here
ok
but I didn't really understand...
like I put both of them in the same main function in different files?
If you want to run the Python files just by clicking them in a file explorer window, there must be a setting for that in PyCharm
wouldnt they run at the same time?
No
thing is server just doesnt stay open
it just opens pycharm
import socket
server_socket = socket.socket()
server_socket.bind(("0.0.0.0", 8820))
server_socket.listen()
print("Server is up and running")
(client_socket, client_address) = server_socket.accept()
print("Client connected")
data = client_socket.recv(1024).decode()
print("Client sent: " + data)
reply = "Hello " + data
client_socket.send(reply.encode())
client_socket.close()
server_socket.close()```
thats the socket
import socket
my_socket = socket.socket()
my_socket.connect(("127.0.0.1", 8820))
my_socket.send("yes".encode())
data = my_socket.recv(1024).decode()
print("The server sent " + data)
if __name__=="__main__":
my_socket.close()
# server.py
... # imports
def main():
... # main logic
if __name__ == "__main__":
main()
# client.py
... # imports
def main():
... # main logic
if __name__ == "__main__":
main()
Weird
Try binding the server on (socket.gethostbyname(socket.gethostname()), 8820)
like this in the server?
Or use the machine's private IPv4 address
Yeah
Make these constants somewhere at the top of the file if you care, so that the program becomes more readable
Do you see the green buttons shown in PyCharm though?
First click the one in the server script, then the one in the client script after the server is ready
Well what happens when you click the green button?
also (socket.gethostbyname(socket.gethostname()), 8820) isnt working
the preivous one does
runs them
Okay
Where is the problem then
no problem rn, u helped
Oh okay cool 👍
yet I still wonder why isnt the CMD working with it
Because of PyCharm's file association
It has set up a file association telling your computer to open Python files in its editor
do u know how can I cancel it?
thnaks
👍
Hey, when i send something (a list of the dir from a computer) and encode it with utf-8, i always get this error UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 864: character maps to <undefined> and i don't know how to fix it, any ideas?
@steady horizonoh bruh check our matual friends
Bruh
i should have had my nickname changed to "Obi-Wan Kenobi" before that last mention 🤪
it's hard to work with the code when only partial code is provided so that we don't know what the different variables contain
for example: what does the variable username used in b() come from and contain? (so i have changed it in my code)
i also had to reverse engineer your intentions with the code in the code1 variable, especially as the expression f'local = "{remotes!r}"' won't do what you want it to even if was written as f'local = "{remote}"' (the variable name i think you intended) as such a value will not be accepted by os.walk(local)
but try something like:
def b():
for i in iter(_stdout1.readline,""):
tot_size, path = i.strip().split("\t")
print(f"DATE {date} : {path} total size is {tot_size} kb")
remote = [f"/home/server2/Desktop/backupdestination/{year}/{month}/{date}/", f"/home/server3/Desktop/backupdestination/{year}/{month}/{date}/"]
dirs = ' '.join(f'"{path}"' for path in remote)
_stdin1, _stdout1, _stderr1 = client.exec_command(f"du -sk {dirs}")
Username is server2 and server3 , I have 2 remote machines so I have named it server2 and server3
tot_size, path = i.strip().split("\t")
ValueError: not enough values to unpack (expected 2, got 1)
b() is a function which helps to get the size of the folder/file from remote @cloud spruce
@mystic haven this is a pattern that you should stay away from as it will only listen on one of the addresses/interfaces and it's very possible that it will pick up another [wrong] address/interface then the one you intended, as such it's very unreliable
unfortunately it's a common pattern in examples on the internet and even in documentation
it's much better to use:
'0.0.0.0' (for ipv4) or '::' (for ipv6) or '' (the empty string, works for any of the two) if you want it to listen to all addresses of that protocol version on the computer
or '127.0.0.1' (for ipv4) or '::1' (for ipv6) if you only want it to be accessible on the local computer
i saw that, and the sum calculations in b() wouldn't have worked
True
yeah, i didn't bother with checking that i got the expected output in the modified b() function
that would need to be added to the code as well
to just debug it you could temporarily change it to:
def b():
for i in iter(_stdout1.readline,""):
print(i.strip())
#tot_size, path = i.strip().split("\t")
#print(f"DATE {date} : {path} total size is {tot_size} kb")
```and see what you get
thanks
also why does this work only 1 time?
server
import socket
import datetime
from random import randint
def main():
server_socket = socket.socket()
server_socket.bind(("0.0.0.0", 8820))
server_socket.listen()
print("Server is up and running")
(client_socket, client_address) = server_socket.accept()
print("Client connected")
while 1:
data = client_socket.recv(1024).decode()
if data == "TIME":
client_socket.send(str(datetime.time()).encode())
elif data == "WHORU":
client_socket.send("BRUH".encode())
elif data == "RAND":
client_socket.send(str(randint(1, 10)).encode())
elif data == "EXIT":
client_socket.close()
server_socket.close()
if __name__ == "__main__":
main()
client ```py
import socket
import datetime
def main():
while True:
inp = input("Command to type: ")
my_socket = socket.socket()
my_socket.connect(("127.0.0.1", 8820))
my_socket.send(inp.encode())
data = my_socket.recv(1024).decode()
print("The server sent " + data)
my_socket.close()
if name=="main":
main()
because you are only accepting a client outside any loop, when that client disconnects the program continues down the code where the program ends
Can I serve both html and websockets on the same port? I have now class Server(http.server.SimpleHTTPRequestHandler): on 8001 and websockets.serve(server.ws_handler, 'localhost', port) on 8008 ... makes my web app hardcoding the ports.
I want ie /ws become a websocket.
yes, you can
how you do it is dependent on the web server and framework where applicable
I currently use SimpleHTTPRequestHandler and websockets module ... is that possible?
I do see websockets upgrade the socket request but I guess SimpleHTTPRequestHandler should start this on /ws
I found this https://websockets.readthedocs.io/en/latest/howto/faq.html#how-do-i-run-http-and-websocket-servers-on-the-same-port 😮 ... case closed 😕
Server side: Why does the server close the connection prematurely?: Your connection handler exits prematurely. Wait for the work to be finished before returning. For example, if your handler has a ...
big shops to it with something like nignx in front of the application servers and reverse proxy to different servers for different paths
and people do mix websockets and non-websockets with bigger frameworks than the one you are using
Thanks for your feedback ... unfortunately my python exec runs on Desktop serving html and websocket ... no nginx/apache 😮 ... Sanic has https://sanic.dev/en/guide/advanced/websockets.html ... going to try that now.
fastapi as well (highly recommended), and i think django does too
I wonder if some of u guys have easy tutorial for twisted
I almost get mad while learning it
🥲
the "Finger service" tutorial in their docs aren't to your taste?
Do you mean the official docs
yeah
that may make sense but I have am urgent 'task' that will be checked by my teacher tomorrow😰
I may need a quick tutorial
i see, the one in the official docs is very detailed and goes slow but is pretty easy to understand, but it takes long to go through because of that
holy correct
have you gotten anywhere with your code or are you just starting?
and what's the task/assignment that you need to complete until tomorrow?
!rule 8 is what we will be following, so we have to stay within those bounds
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
yeah that's alright, it's just complaining or that kind of stuff
it's about writing a server to simulates how a game server which include login/battle/mine funcs runs
no necessarily need for GUI
so, your almost finished with the assignment but you have some bugs to work out before tomorrow, is that it?
I hope so
I have prepared for a delay
If u know some related github projects with readable code or detailed md please let me refer to it
sorry, nothing that comes to mind
that's fine
Hello
I’m greatly interested in coding trading bots. Indeed, I have built some trading algorithms and I aspire to build an investment fund with them. I came to this discord to expand my network and maybe find a business partner! So, if you are interested in coding trading bots, do not hesitate to contact me.
i think your thinking of the wrong kind of networking here
this channel is about network communication between devices and software
Is it okay to use JSON as a TCP application protocol? My current idea is to use a dictionary to store things such as username, command, and message then convert it to a string. I plan on replacing all curly brackets in the text before I insert it so on the server side I can check for the ending bracket '}'. Then once I find it I will convert everything bac using a reversed translation table.
the MTU size is the thing im worried about, with the stream being split up
don't worry about the MTU, tcp will take care of that for your
but i would still recommend calling recv() with a buffer size of 2048 bytes or 4096 bytes on the most common networks and for internet traffic instead of 1024 bytes, so that your code don't need to call recv() multiple times for the content of the same packet in the stream, way to many examples on the internet put 1024 bytes there which just leads to unnecessary number of system calls
well no matter what I have to check for MTU size (custom clients, random data etc) but I managed to fix it
since length checks are on server side i cant limit what comes through
i would suggest having either a short fixed size header that can encode the size of any message that you want to be able to send as one single message
that way you don't have to translate and reverse translate the } characters
data = await reader.readuntil(b'}')
yeah thats what I ended up doing
then I just convert on the server using a reverse table
which i would argue is unnecessary
Well I would have to since a user could input that
and I could add a fixed header length client side but then it could cause a ton of errors and I would have to add even more exception catches with trying read bad data lengths etc
also how would you store clients? I currently have the username as a key in a dict and writer as the value but I feel like this is bad
how do I install pynput in pycharm
depends on the implementation, a list of clients is very common
okay, but should I have the username as the key or the writer as the key?
use a byte that the user can't input
why not just use ascii character 3 to indicate the end of the message
try #editors-ides
I'm sending multiple pieces of data in 1 message so I have to separate it
yes, like with the ascii character 3
Might be a good idea to make a class that includes an attribute for the username and the writer, and then just keep a list of instances of that class for all your clients
unless you want to be sending things to specific usernames usually, then it makes sense to put it in a dict with the username as the key
yeah im sending to specific names
its odd picking a data type though, because half the time I access only the writer and the other time I access the writer through the username. Like {username:writer} when a person wants to send someone a specific message by typing in their username
ill just post my code in a second
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I removed the translation just so its easier to read but thats some of the code
I re wrote a lot of it in the past few hours an removed a majority to start fresh
also, should I include a 'type' into my data? For example with direct messaging and doing other things such as recconecting, it would be a lot easier I think on the client side to display that if I had something such as a type
like...this would be a normal message that gets broadcasted from the client : {'message':message} then from the server to everyone depending on command prefixes etc : {'username':username, 'message':message, 'type':'direct'}
do you know any good proxy list or api ?
hi
Hello, I have problem with connection to smtp servers with port 25. Few days ago I experiment with validation email with connection to smtp server, but now I can not connect to any server. Is possible that the ISP block my port 25 with cause of spamming or should by problem anywhere?
Thanks
it is unfortunately really common for ISPs to block port 25 in both directions other then to their own SMTP servers/relays that they provide to their customers for outgoing e-mail
But now I can not connect to ISPs smtp server
but I can connect to gmail using port 587 so i don't know why he ban only port 25
that's unusual, they often have a few SMTP servers that they host that only their customers can connect to for for outgoing e-mail
and it's pretty common that they only filter port 25 to try to block people from sending spam to SMTP servers out on the internet, that is also why google run their SMTP server for their users on another port to work around that
@normal gazelle i believe discord websockets have this "problem". they send event data in json form which is similar to what you want to do. if you implement websockets (or easily install a library) then you dont have to worry about any of this. unlike TCP, every send call corresponds with a single recv call client side as websockets implement a short header containing the full message length. for efficiency, you dont need to do the HTTP handshake to begin with but thats up to you
your solution of reading until a } appears is just as equally flawed in this sense. what if the client never sends a }? your program would be left hanging, either breaking it completely or invalidating that particular client
I would use websockets but I'd rather solve it doing normal TCP streams rather than skipping over the issue, also I'm pretty sure that's what almost all tcp streams do so I'm not sure how it's flawed, they have to have some indicators that the message line is ending or starting, in my case I'm using asyncio so the input is waiting always
many times they either use a header or a longer multi-byte divider/separator/boundary string that must not exist in the message, that way they only need to translate that string if it where to appear in the stream
I am looking for a peer to peer network mentor.
Hey
I have a code which connect to a network
if previous > state:
print("is critical")
print(f'Because There are no {result3} in {yesterday} comapred to {day_before_date} so the state is critical ')
#riemann.send({'host': 'server', 'service': 'chirag','state':'critical'})
try:
riemann.send({'host': 'server', 'service': 'chirag','state':'critical'})
except:
print("Riemann is not connected and to connect to riemann run the commands ,`bin/riemann etc/riemann.config`,'riemann-dash' ")
if len(previous_clients)==0 and len(current_clients)==0:
print("")
print(f"There are no clients on DATE : {day_before_date} and DATE : {yesterday}")
print("STATE : is Okay")
try:
riemann.send({'host': 'server', 'service': 'chirag','state':'ok'})
except:
print("Riemann is not connected and to connect to riemann run the commands ,`bin/riemann etc/riemann.config`,'riemann-dash' ")
if previous_clients == current_clients:
print("")
print(f"DATE :{yesterday} and DATE :{day_before_date} have equal number of clients , so the State will be OK")
print("STATE : is Okay")
try:
riemann.send({'host': 'server', 'service': 'chirag','state':'ok'})
except:
print("Riemann is not connected and to connect to riemann run the commands ,`bin/riemann etc/riemann.config`,'riemann-dash' ")
previous= state
Exception connecting to TCP socket: [Errno 111] Connection refused
Traceback (most recent call last):
File "/home/server/.local/lib/python3.8/site-packages/bernhard/__init__.py", line 48, in __init__
self.sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
Riemann is not connected and to connect to riemann run the commands ,`bin/riemann etc/riemann.config`,'riemann-dash'
After running the code and trying to resolve issue i get could get till this output
Is there any way where i can get only the last line printed and ignore the remaining part?
Hey,
i am first time using api in python with auth and i have issues how to do it. Can someone help me to understand? I sitting for hours watching tutorials ;-;
https://dev.streamelements.com/docs/kappa/ZG9jOjE4MDk3Njc-o-auth2
https://streamelements.com
OAuth2 enables developers to build applications that utilize data from the StreamElements API. Powered by Stoplight.
Move slower through the material. You might be missing some prerequisite knowledge
Make sure if you dont know a term or idea, you review before proceeeding
Could someone please explain to me what is "reverse tunneling" in layman's language ?
what's the context of your question?
is it specific to for example a ssh reverse tunnel or is it more general as in any reverse tunnel?
in general terms it's a way to reach a resource through another connection that is already established from the other end (a very rough description that might need expanding on)
how can the select module be used with non-blocking sockets, whats the point of putting the sockets into non blocking mode if you use select?
even if select(socket_list) returns immediately when using non-blocking sockets it will give you three lists back which i think does hold quite much value
the first with all sockets that actually does have any data waiting to be read, the second with all sockets that are ready to be written to and a third with all sockets that has any exceptional state (like lost the peer) and then you can process one or several of those lists instead of iterating through all the sockets to check each one of them for such conditions
select() is efficient under linux and many other unix dialects as it's often implemented with backing from other mechanisms in the kernel like epoll
if you're targeting windows with your software you should probably use other methods instead of select(), such as iocp (I/O Completion Ports) with win32file (which interfaces with windows APIs for overlapped I/O https://en.wikipedia.org/wiki/Overlapped_I/O among other things) from pywin32
Or... You can use asyncio
ptables v1.8.4 (legacy): invalid port/service `http,https' specified
What does this mean?
The command I used: $ sudo iptables -A INPUT -p tcp --dport http,https -j DROP
Try using the ports for those protocols (HTTP: 80, HTTPS: 443 I think)
if you want to specify multiple destination ports you need to use --dports (plural) but to use it you also need to load the multiport extension module using --match or -m
something like: -m multiport --dports http,https and names for known services in /etc/services are fine to use by name
yeah, asyncio would be a good option as well for @prisma cobalt
but would probably requires some redesign of the code in general
im making my own concurrent backend :)
Using select or poll you still handle sockets synchronously in the application side of things
!paste the whole file please if you haven't solved this yet and still would like some assistance
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.
as @steady horizon noted, it won't be concurrent
unless you use async/await and it's an I/O bound load or you go multi-process and IPC which would allow you to use multiple cores on a system and be able to handle cpu bound loads as well
even with threads it won't really be concurrent in python due to the GIL, unless you're calling C/C++ libraries that release the GIL and does much of the work outside of python before reacquiring the GIL and without spending to much of it's time exchanging data with the python parts of the library code as that also requires it to hold the GIL
im remaking asyncio
ive already got a concurrent sockets down, i was just wanting to implement the async/await keywords into the project
Have you tried trio?
even if this is kind of network related i think it even more #unix related where it's mainly linux, let's continue in there
Look into generators
I made a simple scheduler with a sleeping function of my own, completely without a library
can anyone recommend a library for making your own proxy/load balancer? Existing solutions always have some little issues (hot load config, performance, either socks or http, etc.)
I know all about them, they are the bases for my current concurrent system
there are so many proxy/revers proxy/load balancer softwares out there which will do a much better job then what anyone and do in python when it comes to performance, which is one of the requirements you list
Then you don't need select or poll or anything else, do you?
yes, i need to check which sockets are ready to read from
You can have non blocking sockets
Someone help@me with some questions
hence my original question, it seems that using select is still of value
generators doesnt require non blocking sockets btw
ask them here in the channel to everyone here and see if anyone might know the answer
can i get help?
i am trying to connect to a server using python
i need to send 3 messages
1 is a post request with the login info and the other 2 are get requests
i managed to send the post request
but no matter what i try to do, the get requests arent working
how it should look like
what i sent
your cookie doesn't seem right compared to the other example
if my host provider doesnt have ipv6
but im using cloudflare, and it auto proxies ipv4 into ipv6
can i just delete my ipv6 AAAA record
in cloudflare?
I imported one cloudflare account into another, and I'm getting some Error 1000
because i think it imported some of the proxied ips from the previous cloudflare account
I replaced most of the ipv4 with my host ip and it's functioning correctly, but every now and then i get the error 1000 and i suspect it's because my AAAA records are not accurate
you would want the ipv6 entries that point to cloudflare to be reachable over ipv6
you do not need any ipv6 entries pointing to the server behind cloudflares servers
i am confused because my load balancer, through my host provider, does not have ipv6
so what am i supposed to put into the new cloudflare account
on a side note how would i even test this, because error 1000 is not an error that pops up every time
but cloudflare does, so if you use them in front of your hosting providers load balancer you should keep the ipv6 entries pointing to cloudflares own infrastructure
i should keep the ipv6 entries in my cloudflare account
and point them to cloudflare ipv6s
?
if you have the usual cloudflare setup where you use them in front of your site and let them take care of TLS termination, DDoS protection and such to protect your site, yes
when i imported the old CF account into my new one, it brought up some duplicate entries, and since my host does not have ipv6, it copied over the proxied ipv6s from the old CF account
for the ipv4s it was easy to debug, i just looked at my hosts load balancer
but for the ipv6s, i am not sure how to fix this, because I can't tell what ipv6 I should have
it imported 2 ipv6s
and i cant tell which one i should use
or if i should somehow find a new CF ipv6 or something
sounds like quite a mess
is the plan to use cloudflare services in front of your hosting providers load balancer or are do you only want to use cloudflare for DNS hosting?
id like to use CF for DNS hosting
or idk actually
my hosts lb is not meant for DNS stuff
thats for certain
if i delete the ipv6s
and toggle ipv6 off in the network tab
then turn it back on, shouldn't it provide a new ipv6
if you want to only use them for DNS hosting and nothing more, then you should remove the AAAA records and just have the A or CNAME record point to your hosting providers load balancer
but if you want to use the cloudflare protective services you should have both A and AAAA records or a CNAME record that points to what ever cloudflare thinks it should point to to reach their cloud services
but what if my LB doesn't support IPv6, how would i point it
because AAAA records are supposed to be IPv6?
l see that CF enables IPV6 by default
as i said, if you are not using cloudflare as a web reverse proxy in front of your hosting providers load balancer and only want to use cloudflare to host DNS you can remove everything that has to do with ipv6 including the AAAA records, then you would let the remaining A and/or CNAME records point directly at your hosting providers load balancer
correct, AAAA records are to IPv6, what A records are to IPv4
probably because their own services has IPv6 support and if you use their other services (not just DNS) in front of your site they can accept both IPv4 and IPv6 traffic to their services and they'll reverse proxy all the traffic to your server (or in your case, your hosting providers load balancer) even if it just supports IPv4 and not IPv6 (cloudflare would in the case of being a reverse proxy take care of the conversion between IPv6 from such clients to IPv4 to your server)
but i do want CF protection
you should keep the ipv6 entries pointing to cloudflares own infrastructure
whats that
then that is another story, then your site will support both IPv4 and IPv6 through cloudflares infrastructure and services even if that traffic is then sent to your hosting providers load balancer only through IPv4
in order to do this
i need to do this
but how can i find what cloudflares ipv6 is? like what ip do i need to find
yes, and cloudflare should either be in direct control of the DNS entries for that or you'll find instructions from then what to point your DNS towards to accomplish that
ok my last question
how can i test this out, and trouble shoot, because the 1000 error only occures randomly
i don't know what this "error 1000" thing is, either it's from cloudflare, your hosting providers load balancer or your server (like your application)
where do you see this error (in the web browser?) and how does it look? (screenshot if you can)
looks like it's from cloudflare: https://support.cloudflare.com/hc/en-us/articles/360029779472-Troubleshooting-Cloudflare-1XXX-errors#error1000
yeah ive looked at that link
If an A record within your Cloudflare DNS app points to a Cloudflare IP address, update the IP address to your origin web server IP address.
There is a reverse-proxy at your origin that sends the request back through the Cloudflare proxy. Instead of using a reverse-proxy, contact your hosting provider or site administrator to configure an HTTP redirect at your origin.```
so my error might not even be because of the AAAA records
i would probably need to see more of your setup to be able guide you how to fix this properly
i went ahead and deleted the AAAA records
but again i have no way of knowing if this error will pop up again
until it does
let's fix this now
if you have opted to set your site to be proxied by cloudflare they will take care of the real A and AAAA records automatically
in the case where you have the proxing enabled you'll instead set only the A records (as your hosting provider does not support IPv6) to point to the load balancer at your hosting provider, you will not be able to use AAAA records in this case but cloudflare solve that for you anyways
this will not be the real A records that the rest of the world sees, this is only for cloudflare so that they know where to reverse proxy the traffic
this should take care of the "error 1000" problem, because for proxied records you can not point them towards cloudflare, that would be a circular flow which cloudflare detects and gives you "error 1000" for
so yes everything is proxied
so just set all A record IPs to host provider
and delete all AAAA records
that should take are of the "error 1000" problem
any idea if i would still get this error if i didnt touch all the other A records for things related to email or stmp
where do you host the e-mail service!
not at the same location as my website
i outsourced the email stuff, like i have a paid outlook
but lets say it might take me a while to figure that out
would i still have the 1000 error?
since it's not routing traffic to my lb for emails and such
it shouldn't, and just make sure no records that are set to proxy point to addresses that belongs to cloudflare and you shouldn't get any more error 1000's
Hello wanted to know has anyone here used pydivert before? Since I'm not aware if Scapy can modify packets before entering the windows network stack?
Hi, i'm really a beginner so can someone please explain me how you would go about making a Json with messages in it readable for humans and then send it to someone on an app like telegram ?
you don't even have to work with json if you want to send stuff to telegram, you can just use the telegram library:
https://python-telegram-bot.org/
https://github.com/python-telegram-bot/python-telegram-bot
or alternatives: https://core.telegram.org/bots/samples#python
yo dudes
i want to make a simple app
that receives and sends messages to my friend who is on a different network
the problem is as u know already u cant bind to a public ip
tried port forwarding
did a bind on the port and local ip
tried to connect to the public ip from my friends network nothing happened
basically
s.bind(my local ip, the port i set in the port forwarding rules )
client side
s.connect(my public ip, same port )
Your destination will be friend_public_ip:port and they’ll need to do a static Port translation which might be PAT on the router.
┌──────────────┐
│ Computer │
│ with │
│ Python │
└──────────────┘
dst ip 4.4.4.4
dst port: (above 1024)
│
│
│
▼
┌──────────────┐
│ │
│ home router │
│ 7.7.7.7 │
└──────────────┘
dst ip 4.4.4.4
dst port: (above 1024)
│
│
│
▼
┌──────────────┐
│ │
│ home router │
│ 4.4.4.4 │
└──────────────┘
'''port address translation
│ converts the 4.4.4.4 to the
│ friend computer IP'''
│ dst ip 192.168.1.1
│ dst port: (above 1024)
▼
┌──────────────┐
│ Friend │
│ Computer │
│ 192.168.1.1 │
└──────────────┘```
@halcyon quartz keep in mind this translation happens in both directions but only the source IP is changed by the local router and the far end router works out converting the destination IP.
it does thanks
sounds like a fun project, good luck 👍
you're welcome
i think the tricky thing will be editing firewall rules and NAT/PAT on each router. The python code will be the fun bit
yeah but at least now i have a direction/ a thing to do i was just lost looking for solutions
ill learn how to do that rn
if you both can reach things out on the internet (which i assume), then SNAT (Source Network Address Translation) is already configured in both of your routers, so you won't have to worry about that part
you should only have to deal with the port forwarding configuration, and maybe firewall rules if that isn't automatic in your router when setting up port forwarding (which it usually is
they you may also have a problem with your computer running a host firewall that you need to open, so that things can connect to the listening port your program sets up, this may very well be your problem right now if you've already done the port forwarding
Can someone show me urllib3 perfect api call funtion?
Something like ```py
def HTTP(method,url,body,header):
Handling all exceptions
in sockets you know how once we establish a connection from the client, you use conn to handle that client. And that client has a different port. As in something like this:
[+] Connection Established 192.168.0.25:55365```
how can you access the second port from the client side; second port meaning the 55365
its the router that performs this port translation for you so there might be a setting in your routes home/admin page @copper swan dont get too excited though since to my knowledge, many routers dont show this setting or allow modification to it
otherwise, you would have to get the server to send you (the client) the port that your using
ohh cool thanks
@prisma cobalt is talking about your typically home router which is also a firewall capable of SPI (Stateful Packet Inspection) and will also apply SNAT (Source Network Address Translation) to traffic going from your internal network (LAN) to the internet (WAN), in doing so it will change the ip address from a private ip (used within your LAN) to the public ip address that your router/firewall was given by your ISP (Internet Service Provider) and the source port for the packet will typically (but not always) also be changed during this process.
This means that the server that you connect to out on the internet through such a router/firewall will see another source ip address and source port then what your client thinks it has.
Within the same network this process does typically not take place, so if the client and server shares the same network they will have the same view of the world then it comes to the source ip address and source port.
If you have access to the socket object for the connection on the client as the variable conn, the quite nonintuitive conn.getsockname() will give you both the local ip address and local port in use for that connection.
This last part is what I think your original question was really about.
very well detailed answer
typed on my phone 😉
I got another question... if your socket program is already connected to a user suppose like 192.168.0.25:4545 and in the middle of communication if i run a connect((host,port)) to that ip and port it still accepts the connection
is it possible to make something that would accept new connections if a prior connection to that server doesn't already exist
i tried using the router assigned port cuz its unique for each connection, but its getting overly complicated if i do it that way
if __name__ == "__main__":
HOST, PORT = "192.168.0.25", 4545
counter_check = 1
while True:
try:
time.sleep(8)
s = Client(HOST, PORT)
s.enable_attempt_reconnect()
if counter_check == 1:
proc = multiprocessing.Process(target=s.start_code)
proc.start() #starting the thread for reverse shell
counter_check += 1
elif proc.is_alive():
proc.terminate() #forcefully close the previous thread
proc = multiprocessing.Process(target=s.start_code)
proc.start() #start a new thread
except Exception:
continue
enable_attempt_reconnect()
def enable_attempt_reconnect(self):
while True:
time.sleep(3)
try:
self.soc.connect((self.host, self.port))
break
except Exception:
continue
anyone?
yoo anyoneee?
it's the client that connects and the server that accepts connections, it looks like you are mixing the two here
also, a client may open more connections to the same server and port if it wants to, browsers does this all the time
if you want to prohibit that in the client you need to add checks in your code before any connect calls so that it doesn't happen
i don't understand what you are trying to do here or why you would want to delay the first connection with 8 seconds
or if even Client() would start a new connection or if you only do that in enable_attempt_reconnect() which waits yet another 3 seconds before doing so
and then after all that you will do your checks and possibly spawn another process
Not a networking problem and the image is upside down...
!rule 8 looks like it would apply here
!rule 7 as it's very much off-topic as this doesn't relate to networking at all
a z- grade for the [total lack of] effort with a upside-down picture of the problem
the proper way would be to post text describing what you need help with and some code of what you have tried so far
we are not code bots that produces code for you upon request
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
if anyone could help me out it'd be helpful
been trying to figure out but just can't seem to get it to work
do you have any example data to play around with?
other than what's available the example above
Unfortunately not 🙁 since I am using this on a game with lan access only
anything else I can provide?
trying to come up with example code, but without any example data and more specifics on what to do this will not be such a good example
!e
import struct
string_50_digits_of_pi = "3.1415926535897932384626433832795028841971693993751"
bytes_close_to_pi = b"\xd0\x0fI@"
bytes_closer_to_pi = b"\xdb\x0fI@"
float_closest_to_pi = float(string_50_digits_of_pi)
# `struct.unpack()` gives you a tuple
# but you just want the float in the first element of that tuple
# `[0]` will fix that
print(f" close: {bytes_close_to_pi} ---> {struct.unpack('<f', bytes_close_to_pi)[0]}")
print(f" closer: {bytes_closer_to_pi} ---> {struct.unpack('<f', bytes_closer_to_pi)[0]}")
print(f" closest: {struct.pack('<f', float_closest_to_pi)} <--- {float_closest_to_pi}")
print(f" 50 digits of pi as string: {string_50_digits_of_pi}")
print()
data = bytearray(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ") # dummy data
data[18:22] = bytes_close_to_pi
print(f" data before: {data}")
print(f" {struct.unpack('<f', data[18:22])[0]}")
data[18:22] = struct.pack("<f", float(struct.unpack("<f", data[18:22])[0] + struct.unpack("<f", b"\xd0\x0fI@")[0]))
print(f" data after: {data}")
print(f" {struct.unpack('<f', data[18:22])[0]}")
print(f" {struct.unpack('<f', bytes_close_to_pi)[0] * 2} = {struct.unpack('<f', bytes_close_to_pi)[0]} * 2 = {struct.unpack('<f', bytes_close_to_pi)[0]} + {struct.unpack('<f', bytes_close_to_pi)[0]}")
@cloud spruce :white_check_mark: Your eval job has completed with return code 0.
001 | close: b'\xd0\x0fI@' ---> 3.141590118408203
002 | closer: b'\xdb\x0fI@' ---> 3.1415927410125732
003 | closest: b'\xdb\x0fI@' <--- 3.141592653589793
004 | 50 digits of pi as string: 3.1415926535897932384626433832795028841971693993751
005 |
006 | data before: bytearray(b'ABCDEFGHIJKLMNOPQR\xd0\x0fI@WXYZ')
007 | 3.141590118408203
008 | data after: bytearray(b'ABCDEFGHIJKLMNOPQR\xd0\x0f\xc9@WXYZ')
009 | 6.283180236816406
010 | 6.283180236816406 = 3.141590118408203 * 2 = 3.141590118408203 + 3.141590118408203
something like that? ⬆️
yeah something like that
doing basic operations like addition/subtraction/multiplication and division with the incoming 4-byte stream before being sent into Window's network stack
data[18:22] = struct.pack("<f", struct.unpack("<f", data[18:22])[0] + struct.unpack("<f", b"\xd0\x0fI@")[0])
```for addition or whatever feels quite cumbersome but it works 🤷
someone with better python skills then me might be able to come up with something both simpler and more efficient
you also might want to go with b"\xdb\x0fI@" instead of your b"\xd0\x0fI@", as the first is closer to pi, at least if pi is important to you
I've wanted to simulate my car facing backwards with the help of packet editing, right now I get an IEEE 754 floating point packets from data[18:22] when I face forward I get packets which are 1.000785 when rounding of it's 1 radian so if I were to make my car face backwards I'd most likely want it to multiply by -1 so that the car faces the opposite direction
that was like my whole thought process
data[18:22] = struct.pack("<f", struct.unpack("<f", data[18:22])[0] * -1)
```like that?
and i removed `float()` from there as it was unnecessary
yeah pretty much
just wanted to know any reason behind using struct.pack and unpack?
struct.unpack('<f', data[18:22]) will convert the four little-endian bytes to a float
then we do math on the float, like: * -1 which also results in something like a float
and then convert it back from a float to four little-endian bytes with struct.pack('<f', ...) (the rest of the expression goes in where ... is in there
all this is really more like #python-discussion, but you are manipulating network packets with this code, so... 🤷
do anyone here know all possible arguments for the data dictionary requests.post(url, json=data) when sending discord messages using webhooks? or just embeds properties
ah makes sense thanks alot
don't know, but i think you might get better help with that in #discord-bots
oh really?
@cloud spruce Just came across this thought not sure why it's not working, I am trying to make the car spin around it's X axis. Here is how I altered
circle_radians = [0, 1.5708, 3.14159, 4.71239, 6.28319] # Goes from 0 degree all the way to 360 degrees
with pydivert.WinDivert("udp.SrcPort = 61572 and ip.DstAddr = 146.19.191.145 and udp.PayloadLength = 62") as w:
for packet in w:
data = bytearray(packet.payload)
for i in circle_radians:
data[18:22] = struct.pack("<f", i) # Testing
#data[18:22] = struct.pack("<f", struct.unpack("<f", data[18:22])[0] + 3.14159) # Changes car orientation to reverse
#data[26:30] = b"\xd0\x0fI@" # Custom Z rot. data
packet.payload = bytes(data) # Writes custom data to the stream
#data1 = bytearray(packet.payload)
#data1[10:14] = struct.pack("<f", struct.unpack("<f", data[10:14])[0] + 1) # Adds +1 height to the car in meters
#packet.payload = bytes(data1) # Writes custom data to the stream
w.send(packet)
X_rot = packet.payload[18:22] # Checking X_rot (front/back)
Y_rot = packet.payload[22:26] # Checking Y_rot (up/down)
Z_rot = packet.payload[26:30] # Checking Z_rot (left/right)
print(struct.unpack('<f', X_rot), "|", struct.unpack('<f', Y_rot), "|", struct.unpack('<f', Z_rot)) # Printing live XYZ rotation.```
I created a for loop for circle_radians so that it sort of simulates going in a circle
but doing that so I can't find my X rotation to change the way I intended it to do so
sorry for the changes
this is how my X coordinate looks
after that change
i don't understand why you would like to loop through circle_radians like that , it should be the same thing as doing:
circle_radians = [0, 1.5708, 3.14159, 4.71239, 6.28319]
circle_radian = sum(circle_radians)
with pydivert.WinDivert("udp.SrcPort = 61572 and ip.DstAddr = 146.19.191.145 and udp.PayloadLength = 62") as w:
for packet in w:
data = bytearray(packet.payload)
data[18:22] = struct.pack("<f", circle_radian)
....
```and now you're always setting it to the same value which is the sum of `circle_radians`, that is probably not what you want
oh yeah there's already a for loop
you probably want to add [0] after each struct.unpack() in your last print line so remove the tuple notation around each value
what is the plan for the values in the circle_radians list?
I wanted to simulate my car moving in a circle
with a for loop
so it'd go from 0 degrees and then finish a full circle and again start from 0 and kept going
your just overwriting the same value over and over, before the change to the code it was the sum of those, now it's just the last value over and over
I assume something like this?
print(struct.unpack('<f', X_rot)[0], "|", struct.unpack('<f', Y_rot)[0], "|", struct.unpack('<f', Z_rot)[0]) # Printing live XYZ rotation.
what you are doing after the changes is this instead: data[18:22] = struct.pack("<f", circle_radians[-1])
hmm yeah even I was thinking it could've ended up as the sum of all those radians but wasn't sure how to rectify it
you need to set different values to different packet payloads
huh what would [-1] do? would it start from reverse?
is there no way to like stop the packets and just assign them new values for every second?
it would always pick the last value of the list, which is the end result of your loop anyways
what about if there is several packets per second?
should all the packets during that second get the same value?
oh hmm yeah makes sense, there might be multiple packets within a second and I can't assign them the same value otherwise it wouldn't even create a circle in the first place... I guess instead the first packet receives 0 degrees, then 90, 180, 270 and 360...
also when I use
data[18:22] = struct.pack("<f", circle_radians)```
without the [-1] I understand that it's going to pick the first value and that's zero but for some reason it's saying
struct.error: required argument is not a float
no, it's trying to give the full list as the second argument to struct.pack(), and that won't work
ohhh
yeah wtf
if I use [0] it starts from the 0th position of the list
hmm my X values still stay the same even though its in a for loop
a well using print(circle_radians[-1]) does not seem to work because then it's only printing 6.28319, shouldn't I create another loop for i in circle_radians[-1] that way it iterates through all the value and assign them at the same time?
what you need is something like:
circle_radians = [0, 1.5708, 3.14159, 4.71239, 6.28319]
radians_count = len(circle_radians)
with pydivert.WinDivert("udp.SrcPort = 61572 and ip.DstAddr = 146.19.191.145 and udp.PayloadLength = 62") as w:
i = 0
for packet in w:
data = bytearray(packet.payload)
data[18:22] = struct.pack("<f", circle_radians[i % radians_count])
i += 1
no, that would just end up setting the final value to the last value in the list
this code will go through the list one entry at a time for each packet and then start over with the first entry in the list and so on
len(circle_radians) would return 5 right?
yes, for that list, but if you keep that code you only need to add more element to the list and the count will update automatically
and % is the modulo operator (the remainder of a division)
oh yeah makes alot more sense now
5%5 will return 0, so it'll iterate to the 0th position of the list
and so on it continues
nice it's working! @cloud spruce but the output seem so jagged, any idea how I can make it readable?
thanks alot so far as well
exactly, counting the number of packets with i and using it to go round and round the circle_radians list
no problem
you where talking about going backwards by taking the current value * -1 on the float
if i'm not mistaking that will just change the sign of the value from positive to negative or negative to positive
that's actually a special case as there is only one bit that signifies if the value is positive or negative and can be done much more efficient with a bitwise xor on that bit to flip it
it would look like this:
with pydivert.WinDivert("udp.SrcPort = 61572 and ip.DstAddr = 146.19.191.145 and udp.PayloadLength = 62") as w:
for packet in w:
data = bytearray(packet.payload)
# flip the most significant bit of the last byte of the four bytes that make up the float to flip sign on the little-endian encoded float
data[21] ^= 128
easy and efficient
Yeah I realised that mistake as well, for some reason adding 3.14159 to the byte stream seems to do the trick as well
Will try this out tomorrow thanks again
just made a small adjustment to my code above and removed the i variable that wasn't used in that example
Also should I just place data[21] ^= 128 after data = bytearray... and what does ^= do? Haven't seen this operator at all, I assume it's for flipping?
^ is the bitwise xor operator (that in python unfortunately can only operate on integers for some reason)
doing a xor on a bit flips it from 0 to 1 or if it's a 1 it will become a 0
128 is "1000 0000" in binary, so will flip that bit first (most significant) bit of that byte
it just happens to be the bit that sets the sign (+ or -) for the float
and ^= does this on the value of the variable and assigns it back to the same variable
a more general solution would be:
extra_rotation = 1.5708
with pydivert.WinDivert("udp.SrcPort = 61572 and ip.DstAddr = 146.19.191.145 and udp.PayloadLength = 62") as w:
for packet in w:
data = bytearray(packet.payload)
data[18:22] = struct.pack("<f", struct.unpack("<f", data[18:22])[0] + extra_rotation)
ssh -f -i "[PEM file]" [EC2_user]@[EC2 endpoint] -L 3307:[RDS endpoint]:[RDS port] -N
how can I write this is sshtunnel through python?
does anyone know how I can prevent from my network console (all the requests) from refreshing
like all these requests go away
Just wanted to let you know, using this the car only rotates 90 degrees from its original position, with 180 degrees it's rotating the opposite way which is what I intended since the start, but yeah was a mistake from my side to think that doing * -1 would just rotate the car at the opposite direction
you need to check the box that says "Preserve log" near the top left of you screenshot
yes, that was deliberate and just an example to make it very obvious if it works as intended or not, just set the value of extra_rotation in the code snippet above to 3.14159 instead and it will go backwards
!rule
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.
Why does my phone not get an IP address on my wifis subnet when I connect it?
sounds like you either don't get fully connected to your wifi or that something is up with your dhcp server that give out ip addresses to the devices
if you use a simple home router for wifi that also is the one that [is the dhcp server and] gives out the ip addresses on the network i would try a reboot of the home router
In the past I have automated a spine leaf architecture. This was easy if all the uplinks are the same speed. Port 1 = Leaf 1. But how would you handle assigning ports and IPs if some of the switches need to be broken out. For examples if you have a spine with 100g ports but some of the switches need to broken out to use 25gb ports.
How do i use and create an API?
an API is very general, it can mean many different thing, but i'm guessing you are ranking about a REST API, right?
for web stuff (including API:s accessed over http(s) i think is probably more suitable in #web-development
i mean like api when you send a request for getting and uploading small data
i want to have two computers that have one python program with the link, communicating with eachother
1x100 Gbps port (let's call it Eth23) usually splits out to 4x25 Gbps ports (like Eth23/1, Eth23/2, Eth23/3 and Eth23/4), you could assume all ports are broken out like that and for those in 100 Gbps mode you can use it like if it was the first sub-port and just skip over the numbers for the other "would-be" sub-ports for that port, then it's easy to count, for example for either the full 100 Gbps port or the first sub-port of that port (really makes no difference) you can number it like (port_num-1)*4+1, for the example above it would be (23-1)*4+1=89
i would say #networks is the right place since #web-development is more focused on frontend web development technologies
checklist of understanding:
1) sockets
2) HTTP
3) API
you need a secure knowledge of the format of HTTP requests/responses before you roll your own api
if your looking to simply use a library then i'd recommend FastAPI
FastAPI, is it some website that hosts apis?
i would disagree, there are quite a lot of flask, django and fastapi talk in there that i would not label as frontend
no, its a backend technology written in python that provides type checking and routes etc for you to implement in your own api
fair enough
to give an example, all of the following is under their "user guide", just imagine what could be in the advanced guide lol
i think im not skilled enough to even think about this i think
not too advanced, just not specific enough, and I was guessing that you question might have been better suited in another channel
ok
what is the end goal for you with your project you want to start?
some sort of chatting program
@cloud spruce How would I automatically cluster the 25 gig ports?
web based or an application or both?
app communicating with api
okay, as you want to go with an api, simple sockets are out, but it will at the same time give you the flexibility to be able to build a web based client front-end later as well if you would like to down the road 👍
what do you mean by how you would automatically cluster the 25 gig ports?
and what make of switches are we talking about here?
then my example naming with Eth23 was spot on 😉
@cloud spruce But in the example if I had an odd number of ports what happens when I add more switches? Will it just leave some ports blank or try to stick a 100g into a subinterface?
you should first make a plan for how you want to organize your ports, either put all the 100 gig ports on one end of yhe switch and the 25 gig ports on the other end of the switch or if you just want to use the first available port regardless of the speed and have them all mixed together
i think you will find it hard to maintain a one to one mapping between port number and leaf number in the long run anyways
for example we found it better to number the leafs in pairs that are running mlag between them to be named like leaf1a and leaf1b instead of just leaf1 and leaf2, and already there one can't maintain the port number to leaf name mapping anymore
i understand if this isn't an appealing idea to you as i also would have liked to keep a 1-to-1 mapping and probably have a little ocd when it comes to keeping things nice and tidy, keeping numbers in order and such to be able to keep track of things without having too look things up all the time, but as I have found it unfeasible to maintain that order everywhere and and at any cost as complexity grows
you might want to have a system such as netbox (open source) or comparable to keep track of it and interact with its api for your automation or if you just keep everything in a well structured database
@cloud spruce Thanks. I was also thinking of keeping the 25g at the bottom of the stack.
i cant find any good documentation on the scapy library does anyone have any links
you don't like the official documentation? https://scapy.readthedocs.io/en/latest/index.html
there is also resources linked on the project page: https://scapy.net/
and on their github page: https://github.com/secdev/scapy
is there anything in particular you need help with?
um @cloud spruce does this code make any sense or do you think there might be ways to improve on this?
Hey @elder cobalt!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Just so to let you know I'm trying to first use a filter in the pydivert.WinDiver to filter out server packets being sent to me and client packets sent to server, what I'm trying to achieve is sort of like to keep teleporting into other players but in reverse I've somewhat achieved it but I can't seem to like keep let's say 5 meter distance in front of my car, when I do data[6:10] = struct.pack("<f", struct.unpack("<f", X_pos)[0] + 5) so that the teleported car stays in front of me 5 meters it works until I start facing my car the other side and the teleported car goes back to my rearview mirror instead in the front of the car
any idea what could be up to it?
Session_ID's is used to identify players in a given car
I want to sort of like mirror my car's driving so far I could mirror it's X rotation so that the teleported car is inverted but I can't for some reason make sure the teleported car stays in front of me at all times
also at some instances I get an error saying that X_pos is not defined, but when I re-execute again it starts working I assume it might be because of how I implemented the logic?
I guess in short how do you make like a mirror? @cloud spruce some sort of a mirror which is in a fixed length/distance apart from the first car?
Can't seem to visualize an idea for this because
If Car A was at (1,1) I want Car B to be at (6,6) in an XZ plane but if car A starts to turn/rotate entirely basically facing the opposite side and maybe if the position changes to (-1,-1) then car B should be at (-6,-6)
feel like I'm getting lost as I proceed
in addition to the x_rot=data[18:22], y_rot=data[22:26], z_rot=data[26:30] rotations you also need the x, y, z position, do you know where that data is located?
sounds like your implementing some kind of spectator mode
sorta but there's so many errors and I feel like the way I might've implemented might be wrong
because I get errors saying that
and I need to keep restarting until it starts working
might be because of this
but not sure what else can I replace it with?
probably, you should implement more checks
when I put a print statement at the very top it sends 4 packets from server, then followed by a 62 which is a client packet
Could it be it's suddenly jumping to the elif statement for client packets ?
and since it hasn't decoded a server packet the client does not know X_pos?
i wouldn't use payload length to decide if it's a client or server packet, i would use ip address or port number to determine that
you know the server port, right?
use that for your comparison
but the payload length just works fine?, since the length is different from a stock server and a modded server(sends more payload compared to stock) and that client will always send a packet of 62
it's mostly udp as well
because if I were to include the port alone then I'd need to again create an if statement for checking if it meets a certain payload length
included debug prints
so it's sending stock server packets but then for some reason when it changes to 62 it says X_pos is not defined
i'm looking at your code now and i don't think you can count on the variables being set like that for the client packets
in the sense? didn't understand you there
yeah, i see now that you have to use another offset for the modded servers, i didn't understand what that was the first time i read the code, but no i understand what that is for
oh no issues
👍
still confused over why once I receive a client packet the whole thing breaks
it would make sense if my first packet was a client packet and then it starts breaking since then I haven't received a server packet
speak of the devil lol
I feel like I need to maybe sort of first query server packets and then after I have some readable ones then pass it to X_pos?
i think you need to debug print the values for the variables when getting a client packet to check what they are
it's just a guess but maybe
I tried putting a print on the server packet as well
so maybe nothing is being assigned at all to X_pos?
I guess that should mean that it's basically jumping to client packets
without decoding any server packets
🤔
yeah xd after assigning a variable in the client for X_pos next error came up saying Y_pos is not defined
yeah, i don't really see why you would use data from the server packets and shove it into the client packet
is that to mirror (with modifications) the actions of another session_id then your own?
yeah
idk I feel like I should maybe start from scratch and maybe this time create my functions?
Kinda glad I got it somewhat working but still far away lol
this task really feels like it's made for C/C++ using structs and pointers to access the binary data directly as the data type it is without copying of data, it would be highly efficient but require the code to be compiled into a binary to run (which would unfortunately also be very OS and arch dependent)
haha, i think i just committed a sin on this server 🤪
on this server Python is always the best tool for the job 😉
Idk how else should I proceed, maybe make a check to see if there's any payload being returned? But then if it's not then what would the client do? Continue normal until it starts recieving packets from server to swap or keep looping the server packet function till it gets some payload from it?
a bruh
so its expected to have a variable defined
@cloud spruce huh I seem to have fixed it?
elif len(packet.payload) == 62: # Client packets
data=bytearray(packet.payload)
#print(len(packet.payload))
try:
data[6:10] = struct.pack("<f", struct.unpack("<f", X_pos)[0])
data[10:14] = Y_pos
data[14:18] = struct.pack("<f", struct.unpack("<f", Z_pos)[0])
data[18:22] = struct.pack("<f", struct.unpack("<f", X_rot)[0] + 3.14159)
data[22:26] = Y_rot
data[26:30] = Z_rot
data[30:34] = X_vel
data[34:38] = Y_vel
data[38:42] = Z_vel
# data[42:43] = tyre_fl
# data[43:44] = tyre_fr
# data[44:45] = tyre_rl
# data[45:46] = tyre_rr
data[46:47] = steer_angle
data[47:48] = wheel_angle
data[48:50] = engineRPM
data[50:51] = gear
data[51:55] = statusFlag
packet.payload = bytes(data)
w.send(packet)
except:
NameError
else:
pass
didn't knew all it needed was a try statement 💀
spent like a whole day on it
that's one way of doing it, but i think the exception handling is a bit wrong
yeah seems like a really hacky way lol
it's like saying yeah that piece of code will have
errors
but still run it
what statement do you think I can add for an exception?
it looks like you use except to catch all types of errors
yeah
that's what i meant with that the exception handling was a bit wrong
you would want something like:
except NameError:
pass
```or what ever you want to do there
you should not catch all types of exceptions, instead be as specific as you can
but instead of pass you probably want to handle it in some way, for example log a message about it
how would I do that though to print the error message other than NameError?
I assume like this?
rather something like:
try:
... your code here ...
except NameError as e:
print(f"{e.name} isn't defined yet.")
I guess the next hurdle is now
making it mirror

already losing hope lmfao but imma start it tomorrow morning
hmm for some reason using this shows
if you want to have the object always be 5 meters ahead of the nose pointing at the nose regardless of where the nose points you need to do some math, more specifically geometry
oh, what flavor and version of python are you using?
the name attribute was added to the NameError exception in python 3.10, so might not work for you: https://docs.python.org/3/library/exceptions.html#NameError
yeah this pretty much
I'm thinking of maybe using the rotation values as a way to determine if the car is facing north, south, east or west. I find them moving from 0 degrees all the way to 180 degrees
do you even need to know which cardinal direction the car is generally facing?
Not sure can try it out tomorrow but it changes from map to map I guess, I think the only way to find which direction the car is facing is through its rotation since that always stays at 0 unless you turn the car
yeah, but isn't the rotation what you really need and not the cardinal direction of the car in relation to the map?
Hi everyone ! I was playing with a python API, and I wanted to change a python command in html command : the command is "request.post(site, arg1=value1, etc)". I would like to know how I should manipulate the arguments of this function for making it a link pls : )
I mean both would work if I could get its cardinal direction then I can create some sort of an if statement where it keeps checking if the cars facing north, south, east or west of the map and then act upon it but I doubt the client or server sends those packets so my next guess would be to only rely on the rotation of the car that way if it's facing backwards it'll apply negative X axis
I was making : "site?arg1:value1&arg2:value2"
a url should look like: protocol://host[:port]/path?arg1=value1&arg2=value2
oh thx dude !!
i definitely think you should go with the rotation of the car to manipulate the packet data
Do you program directly with sockets or is there simpler native modules?
are you asking someone about their specific project or do you mean for your self?
if it's for your self you need to provide more context for your project or task that you want to accomplish
Does anyone know an oauth 1 module for httpx? I tried authlib but i need a realm key in my oauth header and authlib doest support that even tough it says in the docs it does.
I guess I found some relation with rotation and position of X axis but not sure @cloud spruce
-X pos means +X rotation? so if my X position keeps decreasing I need to subtract in order to stay in front?
+X pos means -X rotation? so if my X position keeps increasing I need to add in order to stay in front?
you would also need to change your relative position (in addition to rotation) to the target cars position and rotation
i'm going to guess that X_pos, Y_pos and Z_pos are all little-endian floats just like the angles of X_rot, Y_rot and Z_rot are, right?
yeah
@cloud spruce ```python
if struct.unpack("<f", X_rot)[0] < 0:
print("Positive X")
data[6:10] = struct.pack("<f", struct.unpack("<f", X_pos)[0] + 3.5)
data[14:18] = struct.pack("<f", struct.unpack("<f", Z_pos)[0] - 1.75)
elif struct.unpack("<f", X_rot)[0] > 0:
print("Negative X")
data[6:10] = struct.pack("<f", struct.unpack("<f", X_pos)[0] - 3.5)
data[14:18] = struct.pack("<f", struct.unpack("<f", Z_pos)[0] + 1.75)
elif struct.unpack("<f", Z_rot)[0] > 0:
print("Positive Z")
data[6:10] = struct.pack("<f", struct.unpack("<f", X_pos)[0] + 1)
data[14:18] = struct.pack("<f", struct.unpack("<f", Z_pos)[0] + 5)
elif struct.unpack("<f", Z_rot)[0] < 0:
print("Negative Z")
data[6:10] = struct.pack("<f", struct.unpack("<f", X_pos)[0] - 1)
data[14:18] = struct.pack("<f", struct.unpack("<f", Z_pos)[0] - 5)
else:
pass
Is there anyway to like combine Positive X, Negative X, Positive Z and Negative Z into one whole group? so far after testing a bit it looks like I can only get it to work for north and south but not east and west
i'm a bit busy right now, but i'll come back to you with a general solution instead
it sucks that there's no way to indicate if it's facing north south east and west it's all a huge guess work
-X pos means +X rotation?
+X pos means -X rotation?
-Z pos means -Z rot?
+Z pos means +Z rot?
This is just a huge guess work so I'm sure if I were to try this on any other map it'll fail
i got some math in my head that i think will be a general solution that should work for any map
idk I'm really bad when it comes to math 😅
i really need to know what version of python you have to be able to write this in a good way
and if you would be able to upgrade to a newer version (preferable) if it's a too old of a version to work with all the features i was going to use, or if i would need to write the code for an older version of python
Python 3.9.2
i think 3.9.x will be just enough for what i was planing to write (as i was planing to use some language features first introduced in 3.9) 👍
for better exception handling in other parts of your code you might want to move to 3.10.x (if you can), for example to be able to find the variable name that isn't defined yet in your code using my example above:
try:
... your code here ...
except NameError as e:
print(f"{e.name} isn't defined yet.")
```but it's not required if you are fine with sticking with the normal error message
then can you keep 3.9.x and do:
```python
try:
... your code here ...
except NameError as e:
print(e)
I've used the second code, along with a pass below print(e) works fine by mentioning in the output what error occurs and just continues
you don't need pass when you do print() or anything else there, pass is only needed if you have nothing else in there
it's just like the end of your code, you can just skip the else if all you do in there is pass, as in; remove:
else:
pass
done, thanks for the tip
let's have fun and do some math 😉
what we need is a branch of geometry which is called trigonometry which is very useful when dealing with 2D and 3D space
first i though that i would just give you this little function:
import math
def relative_position_2d(distance: float, rad_angle: float) -> tuple[float, float]:
return distance * math.cos(rad_angle), distance * math.sin(rad_angle)
```but then i took the liberty to rework your code "a bit" (but since i don't run windows and don't have the game i can't really test the code for errors): https://paste.pythondiscord.com/atutakofen
i think there is still more that could be done to improve up on it, but i think this is at least a start
👍 will try it out
any idea what this line means?
if we were to do 1+2 it'd be data[3] meaning it'd print the first 6 bytes, I'm thinking of only printing the one starting from 1st and ending at 2nd
so [1:2] for stock, [3:4] for modded
in python [1:2] == [1], so if you want the second and third element/byte (as the first element/byte is numbered 0) for the stock server
if you want both those bytes is should say [1:3] to get the second [1] and third [2] elements/bytes, as this is very different from many other languages where it's inclusive it can be a source of error if you originally come from other programming languages
o i see
for some reason running the code's disconnecting me from the server 😅
i might have changed too much without being able to test the code 😅
I was struggling with this for over an hour : I have this command in python : "rep = req.post(f"https://api.ecoledirecte.com/v3/Eleves/"+str(self.id)+"/notes.awp?verbe=get",data=payload,headers=self.header)". I would like to make this a link (understand the logic behind it), can someone help me pls ?
yeah no issues just debugging it
btw I see it says if data[1+offset] != session_id will it avoid the whole statement below?
i think you want something like:
rep = req.post(f"https://api.ecoledirecte.com/v3/Eleves/{self.id}/notes.awp?verbe=get", data=payload, headers=self.header)
like assigning X_pos, Y_pos and Z_pos?
the continue statement will exit that iteration of the loop and start working on the next iteration if there is one else start running the first line of code after the loop
and we are checking if data[1 + offset] is not the same as the session_id that we are expecting, and in that case we exit the iteration and start over with the next packet
for some reason if I replace it with packets.send(packet) instead of continue just fixed that tiny error of w.send(packet) the car starts teleporting but it's so sporadic it keeps teleporting in places and bits of the air
this is like my current world position
keeps teleporting everyone on the air
oh, right, otherwise pydivert will not deliver the packet at all 💡
that would be a big problem indeed, i forgot that we are diverting the packets with windivert
also shouldn't we be messing with X and Z position coordinates only?
I want the Y level to be the same as the car I am copying
this line just copies the Z_pos of the target car in to yours, so you should be on the same level as the target car (regardless of the elevation of the course):
data[14:18] = Z_pos
but elevation in game is Y axis?
so you could end up in the air or under the road if it changes elevation
oh, i though that was Z
then we should just change some code
would this much of a change be enough?
i didn't read your comments in the code careful enough
a no issues
that should correct that problem 😄
I've tried tried out the change but looks like it's dissapearing to some part of the map
Let me try printing it's coords and check
instead use this:
if packet.direction == pydivert.Direction.INBOUND:
if len(packet.payload) == 61: # Stock server packets
offset = 0
elif len(packet.payload) > 63: # Modded server packets
offset = 2
data = bytearray(packet.payload)
if data[1 + offset] == session_id:
X_pos = data[9 + offset : 13 + offset] # Checking X_pos (front/back)
Y_pos = data[13 + offset : 17 + offset] # Checking Y_pos (up/down)
Z_pos = data[17 + offset : 21 + offset] # Checking Z_pos (left/right)
X_rot = data[21 + offset : 25 + offset] # Checking X_rot (front/back)
Y_rot = data[25 + offset : 29 + offset] # Checking Y_rot (up/down)
Z_rot = data[29 + offset : 33 + offset] # Checking Z_pos (left/right)
X_vel = data[33 + offset : 37 + offset] # Checking X_rot (front/back)
Y_vel = data[37 + offset : 41 + offset] # Checking Y_rot (up/down)
Z_vel = data[41 + offset : 45 + offset] # Checking Z_pos (left/right)
tyre_fl = data[45 + offset] # Checking angle of tyre fl
tyre_fr = data[46 + offset] # Checking angle of tyre fr
tyre_rl = data[47 + offset] # Checking angle of tyre rl
tyre_rr = data[48 + offset] # Checking angle of tyre rr
steer_angle = data[49 + offset] # Checking steer angle
wheel_angle = data[50 + offset] # Checking wheel angle
engineRPM = data[51 + offset : 53 + offset] # Checking engine RPM
gear = data[53 + offset] # Checking current gear selected
# Checking Status flag of car (eg: - Brake light, head-light, indicator & etc.)
statusFlag = data[54 + offset : 58 + offset]
has_data = True
packet.payload = bytes(data)
w.send(packet)
for the first if statement that is
since i forgot that we needed to reach the w.send(packet) line for the packets to get delivered from the server to your client instead of just being droped
are you sure the floating numbers for position is in meters and not like km or 100m per whole number in the float?
i'm thinking you could change relative_distance = 5 to relative_distance = 0.005 and see what happens
yeah position is in float numbers, but if I were to like let's say using do +1 to my Y axis I'll be 1 meter above ground
tyy
i'm thinking as ml is a subset of ai
yeah, kind of, it was a generalization/simplification
i see, i think the people in #data-science-and-ml might be able to help you better then i can
btw I'm getting these errors should this fix be enough?
its annoying pft
okay, so you are fairly certain that the units the floating number is in is indeed meters then?
yeah
oh, i forgot to do the same kind of adjustments to the other block of code
Yes that's it but I would like to make this a link
Like the one u paste in google
so this is my current game coords, this is what the teleported car is sending 🤔
woops
disregard that post
that looks very wrong
forgot to change my session_id
ah, hahaha
yeah this is what the teleported car is sending
looks like it would be jumping around a lot 🤔
we aren't modifying it, so it shouldn't 🤔
this is basically capturing Car B's Y axis(not the one getting teleported)
I guess I'll just name it as Car A the one teleporting and Car B which is stationary or my dummy subject
do we really have the correct byte offsets for all the fields?
pretty sure we should
data[13:17] is Y position
so since its a stock server
data[13+0:17+0] offset is 0
is this block correct?
@elder cobalt out of interest, how are you sending the binary floating point data over a socket?
pydivert module
not creating my own sockets xd
basically it does the job of opening sockets and changing values before sending over to the network stack
and I convert float to bytes
IEE 754 float values to be precise
the game I'm fiddling with uses little endian might be different for other games
for packet in packets:
if packet.direction == pydivert.Direction.INBOUND:
if len(packet.payload) == 61: # Stock server packets
offset = 0
elif len(packet.payload) > 63: # Modded server packets
offset = 2
data = bytearray(packet.payload)
if data[1 + offset] != session_id:
packets.send(packet) # this packet wasn't for the right car
X_pos = data[9 + offset : 13 + offset] # Checking X_pos (front/back)
Y_pos = data[13 + offset : 17 + offset] # Checking Y_pos (up/down)
Z_pos = data[17 + offset : 21 + offset] # Checking Z_pos (left/right)
X_rot = data[21 + offset : 25 + offset] # Checking X_rot (front/back)
Y_rot = data[25 + offset : 29 + offset] # Checking Y_rot (up/down)
Z_rot = data[29 + offset : 33 + offset] # Checking Z_pos (left/right)
X_vel = data[33 + offset : 37 + offset] # Checking X_rot (front/back)
Y_vel = data[37 + offset : 41 + offset] # Checking Y_rot (up/down)
Z_vel = data[41 + offset : 45 + offset] # Checking Z_pos (left/right)
tyre_fl = data[45 + offset] # Checking angle of tyre fl
tyre_fr = data[46 + offset] # Checking angle of tyre fr
tyre_rl = data[47 + offset] # Checking angle of tyre rl
tyre_rr = data[48 + offset] # Checking angle of tyre rr
steer_angle = data[49 + offset] # Checking steer angle
wheel_angle = data[50 + offset] # Checking wheel angle
engineRPM = data[51 + offset : 53 + offset] # Checking engine RPM
gear = data[53 + offset] # Checking current gear selected
# Checking Status flag of car (eg: - Brake light, indicator & etc.)
statusFlag = data[54 + offset : 58 + offset]
has_data = True
packet.payload = bytes(data)
packets.send(packet)
it's encoded into bytes (little-endian) with:
def from_float(number: float) -> bytes:
return struct.pack("<f", number)
cool thxs
the reverse is just (the last [0] is because unpack returns a tuple that we don't want here):
def to_float(data: bytes) -> float:
return struct.unpack("<f", data)[0]
I have a bad feeling that the Y axis might be capturing something wrong?
hmm offsets
uhh xd
data[14:18] is Z axis
br moment
not sure why Y was there
probably from when you moved my line of code to the right line since i had mixed up what Y and Z was in the game
yeah pretty much
so, might be fine if you just fix that 🙂
oh wtf

