#networks
1 messages · Page 26 of 1
hey, does anyone know a good tutorial for stacks?
sockets*
If I want to make a chat app, without like a public IP, for example, you chat with someone you're machine is connected to their machine (this is all just for fun, nothing serious), do I store their address in the DB locally or what?
again, this is just project I am making just for fun
You can use string manipulation to make sure the entered IP address is local eg it has to start with 192.168.x.x or you can hardcode the server IP into ur program so it will only ever connect to that one specific address
If ur talking about registering users with the ‘friendly name’ like John’s PC then yea a database or a array would have to be used to correlate that name with IP
hey, does anyone know a good tutorial for sockets?
This socket programming tutorial will show you how to connect multiple clients to a server using python 3 sockets. It covers how to send messages from clients to server and from server to clients. I will also show you how to host your socket server locally or globally across the internet so anyone can connect. This uses the python 3 socket and t...
Go with this
Uu
Not answering
Pls help me with Ascii pyfiglet I don't know how to make animation In terminal
it doesnt really explain a lot
@teal vigil This will reallt help you
Ok tell me how to insert payload on image without Rar SFX and FakeImageExploiter
Assuming what you are saying is that you want two client to communicate that don't know each others ip, you could use a server that sits between them that runs on a known IP
Then you can relay the messages between clients though the server, or use it to resolve and pass the IPs across
Thanks a lot ❤️
Is it possible for me to send a request through a dns server?
@merry steppe technically yes, but that stuff usually involve stuff which I should not talk about here.
Dm?
Also DNS server is just like any other server, just that it serves a specific purpose and it's usually locked down with more security and has high bandwidth capacity
@merry steppe I suggest you do some re-search, I won't help you in any way 😉
Basically what I’m saying is I want to use my USA IP and make it look like it’s coming from Canada. I do not though want to use a CANADIAN IP
^ anyone know how we can do this?
You guys understand simple networking, right? @low panther
A packet has a source and destination. If it's TCP, the packet has to return back from the destination from the source.
So, if you send with a source of 192.168.0.1 to destination 1.1.1.1 but you tell 1.1.1.1 that you really are, 172.16.1.1, how can you get the response back? 😛 if you are in control of 172.16.1 you can, but is bad stuff and usually you shouldn't do that
I didn't say that lol
And this is for a cybersecurity project in class
our teacher knows how to do it
but wont say anything
Alright, read up on: https://en.wikipedia.org/wiki/IP_address_spoofing
This it what this implies
not for 4 figs?
Him and I are deadass rn
Multiple grand
For anyone who can solve this problem for us
yeah

^
No black hat shit
@merry steppe not sure what class you guys are taking, but check out https://scapy.net/ for Python
Would u be aware of a golang alternative as well?
Not familiar with Golang :/
@low panther ^^^
If anyone can think of a full solution with every part we described, dm me
Multiple thousand dollar dev project listing
^ yup
just use a canadian proxy server or something
dns has nothing to do with this
otherwise its impossible if you actually want to recieve a response
@slender steeple I totally forgot about proxies, but yes, that is viable. Guess I was overthinking it 😛
Simple things requires simple solutions
@low panther ^
hello, how can I send an interrupt signal to a remote process in python
The process is accessible via netcat
You will need a socket listener that will stop the process when it receives a certain package
Cannot use a proxy though. It would not be our USA IP if we did that
thats...
Thats not technically possible
the USA IP will always look like a USA IP
it's geo location will resolve to the USA regardless
masking the location to appear as somewhere else is what a Proxies' job is so it appears from another IP in another location
Like the only way you can really maybe do this is via spoofing which you're gonna be constructing your own packets for
thats fine.
but again it wont appear as the USA IP
We can spoof
it'll appear as the spoofed ip
Your USA IP will always be a USA IP
you'll just be spoofing the packet as some Canadian IP
Will we need a canadian IP to do that?
well at that point you might aswell just use a proxy
its gonna achieve the same thing
anyone wanna be my friend
where could I go to learn more about this
If we use a proxy we have to supply the proxies then. We would prefer crafting the packets.
you're trying to send a HTTP request correct?
yes
Then you're gonna be in for alot of work
youll likely need scapy todo this in python
and also you'll then need to re-build your http interactions from scratch from these packet interactions
However
i dont think this is possible with http either way
because it'll never sync
what level is this course btw?
cuz i think we're getting to the overly complicating it side of stuff
I think what you're trying do is wayyyyy more complicated than what they would expect you todo for a HS course
You easiest / only method is gonna be using a proxy
cuz ip spoofing isnt gonna work
because the server will respond to an ip that doesnt accept anything
what is the parameter passed into .listen(parameter) do
im trying to create a server that only has one connection to it at a time but will accept connections forever
maybe .listen(1) but does that mean once the connection is over it stops?
maybe a
while True:
socket.listen(1)
#do stuff here
socket.close()
wait no
i dont want to close the server socket
i need to close the client socket
Nah but this is like, beyond what most network engineers can do
if it was just sending spoofing packets
thats one thing
Ok. I understand. Would you be interesting in doing a job for us? Paying heavy heavy money. 4 figs
but you're trying to spoof an ip which doesnt exist or you cant control doing 2 way communication
For the one time job
Low key now matter how much you pay isnt gonna change the fact that you cant do ip spoofing with 2 way communication using 1 ip
Basically we could communicate but not receive the response right
well no
Unless we have control of the IP we are spoofing
you'd send a single packet and immediately fail the handshake
or before that get filtered out by the firewall
If ours is 1.1.1.1 or so. And we want 1.2.1.1 in Canada. We need the other one
If ur referencing TLS etc. we made a client for that
No im referencing the fact that you'll send one tcp packet and fail before you even get to the HTTP protocol because the server will send to a dead ip
So only way to do this would to provide a Canadian proxy?
pretty much
Could we buy a VPS in Canada
i mean yeah
And route All reqs thru it
if you wanna code the proxy maybe look at https://medium.com/@gdieu/build-a-tcp-proxy-in-python-part-1-3-7552cd5afdfe
then
go is a actually a lil easier to write a proxy in that python
https://github.com/elazarl/goproxy also exists if you're feeling lazy
you can use conn.remove()
its removing connected client
interesting stuff
but idk, i dont work with sockets often
i learned sockets in 2 or 3 days
simple as that
Lol, trying to do something really complicated and I only know the basics @ember ledge
how am i able to use putty to connect to the client side?
Does setting up all the headers and cookies while making a request put me in a safe place in order not to get flagged as a machine? Question asked for monitoring ^.
I'm currently trying to find the best way of monitoring without banning my proxies and flagging myself as a machine. I know that most of the sites allow you to request without headers and cookies, but does adding these extra infos put you in a safer place?
Since there are cookies that do expire really often
Line 11 has some unexpected errors, can anyone ractify them?
Ya i saw that @vale vector , and fixed it
Its not accepting the except statement for Processerror
@austere wave I suggest you open a #help channel as this it nor related to networking in Python. You are just executing commands in a shell and then parsing the output.
Yy😔
Also you forgot a ) on line 16
@flint crater could you help me with my question aswell? Ty sir.
@vale vector so you want to simulate user generated requests to hide your software that spits out automated requests?
Have you researched how these software are trying to separate machine vs user generated requests? If not, that is a good starting point to get a good understanding.
Anyway, some tips, don't flood requests. Send all the headers needed, accept cookies, rotate user-agent if using multiple IP-adresses.
Scraping the web is allowed, but do so in fine manner and try to do rate limiting and fire your requests at random (e.g put os.sleep(random.randint(1,10) in there)
Exactly, willing to make request seem as human made as possible.
Currently, i'm adding every header and cookie that the request needs to have, but maybe that's slowing down my script by a bit, what do you think?
As for sleep time, i'm currently sleeping for 0.7 secs since i need really good time speeds in order to stand a change against the competition.
The only thing i think i should upgrade, is the user agent, since i'm using the same user agent for multiple proxies. I think i've seen some websites that do have lists of user agents, but will look into that a bit later.
Another thing i wanted to ask is, does the machine specs also matter when trying to make a request? I know some friends that told me that the better your pc is, the faster your requests will be. My proxies are from Netherlands, since there is the host, but i'm planning to run on a server to be able to run 24/7 and lower the proxies latencies.
But since the server won't have the same specs my pc does, i think that that extra time i'm saving on proxies latency will be lost due to low specs. What do you think?
if you're waiting 0.7s between each request then
it will take 0.7s between requests
your pc will have no impact on that
assuming you're scraping wsb, why are you interested in speed
trying to make a real time monitor to detect any site changes that appear as close as possible to real time
good to know that thank you
do any of you guys know if there is a way to drop the socket connection after a certain amount of time?
Yeah
I don't know the code offhand but you would probably import a date/time package and build some sort of timer out of it and encase the socket connection drop code within that
oh ok thank you
Grab a coffee lol
Maybe you could even find a timer package to import and skip the hassle of building your own timer
😉
Some sort of "if x = 30 // seconds"
"drop socket"
yea I was asking because everytime i try to connect to like a dead server it takes so long before it moves on to connecting to the next
Oh you're trying to implement a timeout function
yea pretty much
sorry for giving you the context only now lol
All good
I am but a mere novice
I know nothing
😉
Hopefully I gave ya ideas though
But yeah I'd make a timer class specifically for the timeout
and call it as you need
would there be any modules i would have to import?
instantiate the object or whatever
Not sure
Google would have those answers
Google Python packages for date/time
timers
Stuff like that
oh ok
thank you again
lol
No worries
Remember
Github is awesome too
Just don't get lost in it
alright
Guys I have a serieus problem! I used os.system("ping -f target"). I started my attack a few hours ago and then quitted right after 10 seconds. It is still sending all tho it isn't even opened yet.
Not sure what u mean exactly if the program is still running and control c hasn’t killed it open take manger and kill cmd and python processes...
ill try to restart my laptop
It worked! all I had to do is restart my laptop
Hey everyone, is this the topic room where I can ask about making HTTP requests for a form-based website?
If not, would the web-development channel be more appropriate?
i suggest to try and see
show us some code and output, then
what’s the best way to become a grey hat in your opinion
!rule 5 i feel like this is a DDOS "attack" and breaks the rules lol
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
@fair dock as stated above, we won't help anything related to DoS attacks. Please don't ask about that here again.
It doesn't matter what the said intend is, since we have no way of checking what they are actually doing
DoS attacks are malicious by definition
also without meaning to be rude it's a completely stupid question
doesn't have any relevance to 'security skills'
Let's not share malicious projects too
I mean, they mentioned that it was an "attack"
I was pinging my own ubuntu server :/
Alright
Why don’t dos instead of ping if you want to see how strong the server is
I already tried different methods. I wanted to try the ping method
Hey guys, I want to try and make a script to alert me via a discord webhook if an attack is detected on a my OVH.
But how would I make the script detect an attack?
Any help would be appreciated.
Hi everyone. I m new and i just started coding python. Can someone tell me or give some tips where i should start and the direction i should go?
Not sure what is OVH is but you can check if theres a API that you can use to get data from OVH
/\ OVH is a hosting company they host VPS and servers
I mean there are lots of types of attacks if u mean every time someone attempts to SSH yeah that’s possible or if it is for a every specific attack?
When I use socket and have an android app with Kivy, the app seems to crash when I attempt to get the IP address of the device.
Crashes with both
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
and
client_ip = ([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
Is this a problem with socket on android or just the wrong way to get an IP?
error msg?
Hi guys I was wondering how I could attack my brother phone does anyone know how
if s.connect fails then s.close will also fail
so your error catching is a bit flawed
do you get an error output
I was wondering how I could attack my brother phone does anyone know how
Does anyone have links to where I can learn how to use sockets to calculate the ping. It's for coursework, we've been given no guidence just a few slides explaining what ping is. I've read the python page on sockets but I'm still lost.
We won’t help with that here
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
Learning purposes only
Do you know how to
It doesn’t matter what you want it for
you've just stated that you're doing it for explicitly illegal purposes
why would you do that before you say it's for educational reasons
My brother is allowing me to do it
Therefore it is legal
@storm saffron would you know how to do it
what are you even talking about
you could hit it with a brick
that would count as an attack
if you mean 'hack into it and make squiggly hacking things appear' then there's not much point
Do you know about network engineering
i know a bit
Want would be your advice on becoming one
a network engineer?
that's not really a thing
at least in the sense of what you seem to think it is
Hi question, how can I increase the max file size at websockets server and client?
I want to send about 3mb tops, base64 image and some other stuff
Already solved the problem, thanks anyway
I get errorno 13 permission denied.
I narrowed it down to the android permissions, but trying to figure out how on earth how to do that
It seems I need to ask permission for Network access and/or Wifi access
What are you asking for? It looks like talk in offtopic channel
Hello, not sure if this is the right channel for seeking out some socket, pickle answers. If not please point. = pointed, thx
hello there
any one know a way to block ip perm to connaction with cmd
or something like that
If ur on windows it’s advanced firewall options not CMD I think u can use power shell but that’s just making it harder for urself. Btw this is a python discord
Why would a websocket use bytes instead of JSON?
binary is more space efficient
yea i know i'm coding that on python
by exec()
@halcyon arrow the prbolem is when i block the connaction its still
Not sure if this is offtopic, but i don't know where else to ask. I'm trying to use NGINX to serve a static site (it uses a Flask API, so technically python related). It was working fine, but when I restarted, it stopped using CSS and JS.
It returns 404.
This is my config for the site (default):
This is the nginx.conf: https://pastebin.com/V0rLFDEv
This script helped me fix any issues with package managers on my vps
where is the best way ti learn network
<@&267629731250176001> malicious disguised shell script /\ 
i've started writing reports by hand 
not particularly malicious
We have message logs, we'll look into it
Sorry, I forgot a word in my statement lol
you meant ddosing?
thats illegal and nobody is going to teach you how to do that here
your better off
hey
i want to make something like discord (but simpler) in python
which network protocol do i use
Are you asking about text-chat or voice/video-chat?
text chat
If you are asking about TCP/UDP then as far as I know you can use UDP nowadays because it's faster than TCP but you should implement retransmission for example on your own
ok how to do it ?
is this correct https://wiki.python.org/moin/UdpCommunication
Yes, it looks okay
ok
so what about the server ?
do i need one ?
also @clear bobcat it says
If considering extending this example for e.g. file transfers, keep in mind that UDP is not reliable. So you'll have to handle packets getting lost and packets arriving out of order. In effect, to get something reliable you'll need to implement something similar to TCP on top of UDP, and you might want to consider using TCP instead.
Like I said, you should then implement some features which are built inside TCP protocol
Which library do you use for networking ?
I don't know what do you want to achieve - learn something new or just build working solution
how tho ?
For example TCP has retransmission feature (UDP not). TCP has ACK for message (UDP not).
If you don't have knowledge about network protocols you can use TCP and forget about many problems that you are going to have with UDP

I am working on a tkinter client. But whenever I enter a port number to connect with sock.connect(ip.get(),port.get()) it says port.get() has to be an int(got type by str). I entered 80 in my port field. Any solutions?
Just try int(port.get())?
Remember about ValueError when it's not an integer
ok thank you. I will try that out
Hello im working on static routing for a network was wondering how you would decide on the optimal path
working in core network emulator on VM
ribonucleic acid?
The optimal path is usually determined by some kind metric. Metric being “fewest hops” or “most available bandwidth” or “lowest latency” or a combination of each. Most dynamic routing protocols determine the metric for you automatically albeit in different ways. In the case of static routing, you typically forego using metric and forcibly send packets down a specific path. So to somewhat answer your question, whatever path gets the packets to their destination.
ok ty a lot
Hey does anyone have knowledge about the TinyTuya library
.
Do you have any ideea what couldve caused this? I have a try catch sentence in my code, it triggered the exception but the program still failed to move on and make another request :
try:
code
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as err:
print(f"\nSite took too long to respond./ Proxy {proxy} might be dead xd. Monitoring: {keywords}.")
I was monitoring the website for around 6 hours at that time, 10 secs between requests and i was running with 50 proxies, timeout delay for requests module being set to 40 seconds(in case the website didn't respond, which it did). Do you think that was just bad timing related and i should've added those 2 proxies to the error list or it actually banned me?
BTW, i was running other instances at that moment on other websites and proxies were workin and didn't get any error so it makes me think it was a proxy - website related problem.
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.pydis.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.
website related problem means it has a vulnerability?
hey where can i delete the Internet?
ok
bruh
Anyone around?
hi
even better would be asking your question
so people can figure out whether they can help you before committing to helping you @neon kelp
but the 2nd one is defininitely still better
Fair enough:
I'm trying to subnet this address,
172.18.0.0/25
Would it have 2 subnets or 512 subnets? And would I start subnetting at 172.18.128.0 or 172.18.0.128?
It's part of a VLSM scheme, it has 125 hosts, so hence the /25 CIDR value.
It has 128 increments.
You always start at the network address (what comes before the slash), so 0.0 in this case
also there is only one subnet here, with 128 hosts
approximately.
...
say i am logged in on my browser, and I want to automatically copy some details from a request i make in a session, like csrf token etc. is that at all possible
@severe ocean Thought there would be at least two subnets?
there are many subnets out there, but only one per CIDR address. A CIDR address IS a subnet.
@neon kelp
172.18.0.0/25 = 172.18.0.0-172.18.0.127
of course, you can subnet those further, to 64, 32 addresses, etc
but the CIDR would change
alright. They are saying that if you take a (rather arbitrary) subnet of /16, and divide it into 512 subnets, you will get the /25 subnet. I don't know how this information is useful...
what is the question you are trying to answer?
I'm trying to do a VLSM of this network, and here's what I have so far:
172.18.47.128/17 – Original IP Address
Network address is 172.18.0.0 (Class B)
125 hosts- 172.18.0.0 /25 11111111.11111111.11111111.10000000 (128 increments)
60 hosts- 172.18.0.128 /26 11111111.11111111.11111111.11000000 (64 increments)
28 hosts- 172.18.0.192 /27 11111111.11111111.11111111.11100000 (32 increments)
12 hosts- 172.18.0.224 /28 11111111.11111111.11111111.11110000 (16 increments)
2 hosts (linking network)- 172.18.0.240 /30 11111111.11111111.11111111.11111100 (4 increments)
2 hosts (linking network) – 172.18.0.244 /30 11111111.11111111.11111111.11111100 (4 increments)
Then I have to subnet all of these out, which takes me back to the question of 2 subnets or 512 for the ip address of 172.18.0.0/25.
oh wow, i do not know this thing of subnetting a subnet at all. sorry...
@neon kelp maybe I can help? It looks like your post just above asap already has things subnetted out pretty well here
@rugged thicket Well,
it's not necessarily that portion I'm struggling with,
I'll show you what I am.
So,
do I use 512 subnets here or 2 subnets?
It's a class B in it of itself,
but it has a CIDR of 25,
that's why I'm confused.
I know the rest of it.
so classful networking isn't really a thing anymore
classful back in the days would mean that it would only be what that class was.
VLSM/CIDRs inherently break that model, despite people still using the terminology
in current state, you have 172.18.47.128/17
if you own this IP, you can subnet that out as far as you'd possibly want
The only issue is I don't know how many subnets 172.18.0.0/25 has.
Or would have in this scneario.
scenario
well 172.18.0.0/25 is the subnet
you could then break that further apart, but that in and of itself is a subnet
yeah, Q1 in your picture is weird
are they saying how many /25s you'd have within the /17?
They're asking how many subnets I'd have within my borrowed host bits, so essentially the 1s in the Mask to the second power.
So thus,
2^9th power.
Which is how I came to 512,
however,
if this was a "class C"
the third octet would be excluded,
leaving me with just 2^1 power, which is 2 subnets.
My professor has pneumonia, so unfortunately, they're out of the question at the moment.
if it was a true class C, then it wouldn't be able to be a /17 in the first place
are they still teaching classes?
Trying to,
but they let us out early.
So, based on my information, would you go with 512 or 2?
classes are based on the first bit being used
so if this was classful, it would fall into the B range
it's very unfortunate they are teaching anythign about classfulness anymore, hasn't been a thing for like 15 years
I'd go with how many /25s there are in the /17 and stick with 512 in that regard
Fair enough.
But,
for learning's sake,
if I had a 192.30.0.1 (Class C),
/25 CIDR
I'd go with 2 subnets, right?
you couldn't have a /25 CIDR in a class C
by definition it would only ever be a /24
VLSM cannot be used in classfullness
Well, 1 subnet then
yup it would be 192.30.0.0/24
Alright,
I'll go through the rest of this with this in mind.
I appreciate the help,
I'd ask the professor but,
I'm sure they're asleep.
By now.
sure thing, take it easy. feel free to PM if you have any questions, my main job is network engineering, joined this group for the python stuff!
Neat, is it alright if I friend to make things a little easier?
See, my passion is more on the side of malware analysis, but I'm still a student.
sure thing
nice, good field to be in
idk if its the right channel to ask that question, but what s the most optimal way to parse sites that require javascript to make required data appear? I kinda feel like selenium would be kind of overkill
Scrapy?
Hi everyone, I'm trying to make a little http(s) proxy in python. The http works fine, but I have issues with https. If anyone is available for helping me, I'll detail the issues
how to make it such that the server will accept all connections made to it
the server code i have is
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
print(data)
if not data:
break
conn.sendall(data)```
the client code is
```py
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
str1=input('message ? ')
byt1=bytes(str1, 'ascii')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(byt1)
data = s.recv(1024)
print('Received', repr(data))
```this is the code i got is it wrong or what can be changed ?
@bold pond define accept all connections made to it
Perhaps you mean to say that another computer in another network can connect to the server? Then look into the IP-address you are binding your server to.....
https://stackoverflow.com/a/39314221/3314139
oh so if i get the ip of client it can connect to the server ?
and also after defining accept all connections made to it
I meant define as re-phrase your question.....
Also state your issue
As far I as I can see, you only allow connections from localhost (127.0.0.1) on your server so only clients on the same machine can connect to the server.
E.g if you host this on raspberry pi in your on network, your own computer can't connect because it only allows connections from the local machine (raspberry pi) so you will have to bind it to another IP on the server e.g 0.0.0.0 and then update your client code to connect to the IP-address of the network interface that is connected to the local network
so getting the client ip and binding it is better right ?
## importing socket module
import socket
## getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")```
i found this code is it alright if i use it and bind it to my server
or i need to accept all connections
what?! You bind the server to an IP that is local to it or maybe even 0.0.0.0 it will allow connections from everyone.
Then you have to tell the client to connect to the IP address that is on the network interface of the server
I suggest you do some reading.....
Without picking up a book here is some resources:
https://realpython.com/python-sockets/ sockets & python
http://faculty.gineecorp.com/Assignments/Sockets.pdf general socket usage and networking
https://docs.python.org/3/howto/sockets.html more about sockets in python
ok i will read it ty for your help
@bold pond that code looks alright, it will bind to the assgined ip address of the machine of what ever it has (e.g 192.168.0.2)
ok
still nobody for an issue making connection over https with socket and ssl ?
I made a client and server with the socket module and made it so when you type a command at the server end it would execute it on the client end and there would be multiple clients connected at one time and I want the output of the command to go back to the server but only one of the output goes back to the server and the other one gets printed when I run the next command can someone help me, please?
SERVER:
import socket
import threading
CLIENTS = {}
host = "127.0.0.1"
port = 6969
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print("Server started")
def client_cmd(conn):
while True:
client_send = input("Command for clients: ").encode("utf-8")
if not client_send:
break
for client in CLIENTS.values():
client.send(client_send)
data = conn.recv(2048)
print(data.decode("utf-8"))
del CLIENTS[conn.fileno()]
while True:
conn, addr = s.accept()
CLIENTS[conn.fileno()] = conn
threading.Thread(target=client_cmd, args=(conn,)).start()
CLIENT:
import socket
import threading
import os
socket = socket.socket()
host = '127.0.0.1'
port = 6969
try:
socket.connect((host, port))
print("Connected to the server")
except:
print("There was an error connecting to the server please try again")
def Communication():
res = socket.recv(1024)
res = res.decode("utf-8")
try:
output = os.popen(res)
sender = str(socket.getsockname()) + " sent back>> "
socket.send(sender.encode("utf-8") + output.read().encode("utf-8"))
print("command executed and sent to server")
except:
print("Command not found")
socket.send("Command not found".encode("utf-8"))
for _ in range(100):
threading.Thread(target=Communication).start()
Oh
$vib (
hello, I'm trying to run a simple game server on my local machine on port 5555 and was trying to figure out port forwarding. But I'm confused about the External Port Number field in the bottom left. Does it mean the port number of the client from which the connection request would be initiated or what?
guys does someone know how to run multiple ssh commands with paramiko?
no, it means the port number that is attached to your public ip address.
port numbers attached to my public address? can you please elaborate a bit more and what should I input in that field. I'm really a beginner
no if you want to connect from the same network you need the private ip address
if you want to connect from over the internet in the server side of it you need a private ip address and in the client the public ip and port foward on the server side
you need to port forward on the same port you used in your code
if you want to connect from the same network you will use the private ip address
if you want to test the thing on your network you can just use the loophole address
no need to port forward for that
if you have trouble you can send your code i might be able to help you
port forwarding is just to connect from other networks
isn't port forwarding just a NAT manager
literally
i mean
NAT does port forwarding
but the interface is just managing NAT here
if you port forward you just tell your router to direct data comming in to your computer in a specific port
if you dont do it the router doesnt know where to direct the data so it doesnt respond and the connection is closed
nave do you have a recommendation to places i can host apps that use networking?
say i have a game and it has a client file and a server file, what service do you recommend for hosting the server file?
well ye but i feel it will make my server slow and maybe prone to attacks
id say thats your best bet
Thanks.
np
You can have the best server available, but bad code will always be prone to bottleneck slowness.. Optimize your code and make sure to test, test, test.
👍
We're not talking 1-1 testing, do a broad test. E.g 100 connections at the same time sending different types of request, is your server able to handle it within reasonable time-frame < 1-5 seconds? @steady horizon
Good luck!
idk how i can even test 100 connections
do they have to be meaningful and responsive
cuz 100 cmds is a hassle
You write a simple client.py that is using threading to spawn multiple clients connection multiple times ;-)
Ah.
Don't even have to open cmd 100 times.
100 connections might be to much... depends on your scale of software and target....
definitely
Try targeting 10 connections :-)
Should be fine.
if it's like a game should i make a lobby server, or multiple lobby servers, that later connect you to some other game server?
i wonder how do i even manage that
ez
1x server, 1x client, do your 1-1 testing first. Get simple things going, then think about how you would handle multiple clients. Optimize code, do some more testing with 2-3 clients at the same time (look into Twisted for example). Continue to optimize then write more code (new functionality ), test again... rinze and repeat
Also if I'm making a GUI app or whatever, really, should I have a thread for the networking stuff an another for the window loop?
Once you feel your code is ready, use Linode to host the server for the world to try it out!
what do i do if the server crashes?
@steady horizon I've never developed a game myself, but yes, normally you have a game loop that is non blocking the main thread and gui thread is separate
(Don't take my word for it!!)
Last time I tried making a chat app with tkinter I just wrote my own main loop in a while loop at the end of the file.
It worked until I realized server sockets close the client sockets when the client sockets send empty data.
Also just how bad do you think making a simple "shared mouse position" program will be using UDP instead of TCP
I've never actually tried using the UDP part of the socket module.
Can I lean on Python to build protocols or for distributed computing?
- Do you know when it started crashing?
- Not enough ram possibly
- A system scan check is probably the best thing to do
Does anyone else have any suggestions....
does anyone know how to setup an api where a cnc can send commands to the api
Um ... not sure if this is the place
but
is there a way i can take the data on a 192. address and send it to a 172 address on the same device
Like if I ping the 192 address from a node 1
have node 2 see it on the 172 address
sure, we would call something like that "routing"
can you clarify "same device"
which parts of the process are bound to this "same device"
Its a tap
SDR 1 has ip 192.xxx.xxx.xx1 SDR 2 has IP 192.xxx.xxx.xx2, and ip address 172.xxx.xxx.xx1. I want to move the data from ip 192.xxx.xxx.xx2 to 172.xxx.xxx.xx1 on sdr 2
i wanna learn networking but im brokey 😦 do you guys know of some free courses that at least get me started?
is there anyone who is bored?
programmers are never bored ... just frustrated 😛
Hey guys don't mean to bother but how do i get rid of my suppression in a voice channel ?
actually meant to put this in the general chat my bad.
Routing... on Linux check out iptables
can relate
Why I am not receiving any packets? BTW i am trying to send packets to somebody that it's not on my wi-fi
import socket
import random
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = "my_ip"
port = "port"
data = random._urandom(1024)
while True:
addr = (str(ip),int(port))
sock.sendto(data,addr)
pls help
nmap3.exceptions.NmapNotInstalledError: Nmap is either not installed or we couldn't locate nmap path Please ensure nmap is installed
@ember ledge your code has many typos you might want to fix that and also if you want to send data to someone not in the same network you need to port forward a port on your router to your computer and start the server on that port and let him connect with your public ip address and same port you opened
THANKS
u need to install nmap
I hve installed it
can someone give me good resources (links, videos) to understand APIs etc. better?
where should i install nmap3 to aviod this error.......nmap3.exceptions.NmapNotInstalledError: Nmap is either not installed or we couldn't locate nmap path Please ensure nmap is installed
how have you installed it
the fuck @ember ledge
i have a question how is flooding performed if the victim needs to connect to my server
@flint crater sadly they didnt work ended up using quagga
I made a tap and then quagga routed the data
Quagga works too! 😄 Haven't touched that in years...!
How would you do it with ip tables
I tried adding the desired ip to the route table and it didnt work
I guess that's true... was using it for a python script though lol
It doesn't seem like there are many people in general that know networking stuff though
I asked many many sources and only the hackrf guys knew why i wanted to do it and how to do it
maybe /r/homenetworking/ or /r/homelab or even /r/networking
ANyway, true, this Discord is mostly beginner stuff, not a good source for advanced topics... but sure, you can implement native routing in linux, after all, quagga is a software that runs in userland so.
@sly fulcrum wait.. you mentioned SDR, you not trying to simulate a BTS or anything? 😆
srsLTE :D!
good guess though spot on coldice!
I tried homelab, but talking to them they said that they are mostly home like homelab a few of the mods were talking to me and said that they don't really get involved with the coding stuff
i have a question how is flooding performed if the victim needs to connect to my server
I have a question regarding stomp py and ActiveMQ. I am fairly new to networking protocols so please forgive my basic question. Basically I have made a tool that creates a client ID on launch which is used to create a listener. I can see it appear on ActiveMQ’s server. The client ID has some component of UUID because it is created per instance of the tool launch. Anyways, sometimes the tool can crash so hard that it does not execute the disconnection codes on tool closure so there remains rogue listener(s). I am wondering what would be a good way to disconnect from those stray/rogue listeners? Right now I either manually purge it on the server site or log off/login works too. Any ideas would be welcomed!
@ember ledge what do you mean by flooding?
flooding it's a Dos attack that sends a lot of packets to an ip adress to make their internet slower
You know thats illegal if he doesnt accept to it
hi guys im trying to open a port on my VPS.
using nmap, I can see the port is open, although using a port checker (like https://portchecker.co/), it shows the port as closed.
what am i doing wrong?
Note: I have my server running and listening to the port
but i guess you can just start a bunch of threads at the same time that ping him
@ionic forum how have you opened the port
Hey I ended up opening it I just couldn’t connect.
Got working now
ya i know i am just working on a network framework and i need this tool to complete it
how can i stream images across sockets
Okay guys, socket question
We have a script with uses the socket module to create udp sockets for uni cast and multicast. We’ve noticed when we try and subscribe an interface ip using setsockopt(sol_ip) it doesn’t work with a network cable unplugged. However when we connect to a device (eg switch) it does
However, if I connect it to a device, then disconnect it and then run the setsockopt, it works!
Hello everyone, I am going to start a project to send the audio of a radio station through a web page and a client apk, any suggestions or documentation that colleagues suggest me?
I don't thing flooding has anything to do with "Connecting to your server"
lol. Depends on programmer 👌
I'm trying to use no-ipy but there's actually no documentation, i wanna pick up the ngrok address and then turn it into a fix no-ip address
im using google colab and i dunno how to pick up the ngrok address and how to use no-ipy
Anyone knows which network zone is VPN server in? DMZ or Intranet or Extranet
"Connecting to your server...
And I'm a girl btw haha"
exact i mean how to send packets if my other computer is not connected to my server or my internet
sorry from get in, but what did you mean? make a computer not connect to a network send packets
i am trying to send packets to another computer without the computer being connected to my wi fi or my server
but it already does that, no?
my code doesn't work
ah, its specific protocols
i turned firewall off and it still doesn't work
wait what
i don't understand
maybe i am just stupid
i dont know what I talking about, im just curious about recognition of packets
their UDP i think
So i think it's impossible or i am stupid
wait do i need to put my interface in monitor mode
to use wireshark
i will try do that with an old android device
to run my code?
im dont have knowledge enough
anyway thx
I will learn more, maybe I can give a little help
if u don't want it's not needed
@ember ledge send your code and maybe i can help you find the problem
when i stream image data over sockets, more than half of the image received by the client is gray blocks. how can i fix that?
with open("cache.jpg", "rb") as imagefile:
img_bytes = imagefile.read()
size = len(img_bytes)
print("Sending image size to client...")
CLIENT.send(f"SIZE {size}".encode("utf8"))
response = CLIENT.recv(2048)
if not response:
stream_image_data = False
continue
if response.decode("utf8") == "GOT SIZE":
time.sleep(0.2)
print("Sending image data to client...")
CLIENT.sendall(img_bytes)
response = CLIENT.recv(2048)
if not response:
stream_image_data = False
continue
if response.decode("utf8") == "GOT IMAGE":
print("Sent image to client successfully!")
elif response.decode("utf8") == "STOP FOOTAGE STREAM":
stream_image_data = False
print("Stopped sending video data!")
elif response.decode("utf8") == "STOP FOOTAGE STREAM":
stream_image_data = False
CLIENT.send(b"OK")
print("Stopped sending video data!")
``` this is my server
size_msg = s.recv(2048)
if not size_msg:
self.go_back()
break
try:
size_decoded = size_msg.decode("utf8")
except UnicodeDecodeError:
continue
if size_decoded.startswith("SIZE"):
size = int(size_msg.split()[1])
print(f"Received image size: {size}!")
s.send(b"GOT SIZE")
img_data = s.recv(size)
self.image_complete = False
with open("footage.jpg", "wb") as imagefile:
imagefile.write(img_data)
print("Received image data!")
self.image_complete = True
s.send(b"GOT IMAGE")
``` and client
sorry for the indents
nvm i fixed it
i did this ```py
img_data = b""
while len(img_data) < size:
packet = s.recv(4096)
img_data += packet
img_data = img_data[:size]
i tried setting my buffer to something large but it didnt work
am i able to get every incoming request being sent to my network in python?
Hi, so I'm trying to update a Python script. Basically I'd like for example when using sockets, so there's a server and one (or more) client(s). I would like that when I modify the client script on my pc, that it also modifies it on all the other pc's where there is the client script. (I start with sockets, I don't know much yet).
Oh okay i'll see that, thx !
Working with APIs. I want it to print the teacher name like this:
Teacher Name: Colin Malcolm
The result the API gives me is this:
'type': 'media', 'contentId': '60066ca7f6a508429a66d69d', 'teachers': [{'name': 'Colin Malcolm', 'role': 'teacher', 'id': '5f4d1c12c12ff43f3267afcc'}]
I watched like 5 youtube videos and I still couldnt get it.
For reference, I retrieve my API data from this line:
complete_data = requests.get(api_link, headers=send_headers).json()
When I do print(complete_data) it works and prints the whole thing.
so you want the first element of the teachers list
and you want its name value
assuming there's only one teacher
so complete_data["teachers"][0]["name"]
if anyone knows how send api post requests to launch remote shell commands hmu
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
hello
import socket
import random
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = "my_ip"
port = "port"
data = random._urandom(1024)
while True:
addr = (str(ip),int(port))
sock.sendto(data,addr)
this is my code so far
dm me in private
ok
your kidding right?
can someone suggest me a reliable source to start learning concepts of networking
do you like this portscanner that I made:
from queue import Queue
import socket
import threading
target = "127.0.0.1"
queue = Queue()
open_ports = []
def portscan(port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target, port))
return True
except:
return False
def get_ports(mode):
if mode == 1:
for port in range(1, 1024):
queue.put(port)
elif mode == 2:
for port in range(1, 49152):
queue.put(port)
elif mode == 3:
ports = [20, 21, 22, 23, 25, 53, 80, 110, 443]
for port in ports:
queue.put(port)
elif mode == 4:
ports = input("Enter your ports (seperate by blank):")
ports = ports.split()
ports = list(map(int, ports))
for port in ports:
queue.put(port)
def worker():
while not queue.empty():
port = queue.get()
if portscan(port):
print("Port {} is open!".format(port))
open_ports.append(port)
def run_scanner(threads, mode):
get_ports(mode)
thread_list = []
for t in range(threads):
thread = threading.Thread(target=worker)
thread_list.append(thread)
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
print("Open ports are:", open_ports)
run_scanner(100, 1)
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
this whole channel is just illegal shit lol
Anyone help-me?
I am not able to send emails through python
I'm using google colab
Analyze my codr please for those interested
wut
u good bro
error messages?
this is the first message i get all day 
who's experienced here with websockets?
what is your question
so i try to connect to a text chat websocket via python, i'm not too familiar with websockets but i'm just imitating chrome requests
await websocket.send('2probe')
print(await websocket.recv()) #I get response
await websocket.send('5')
print(await websocket.recv()) #no response
i presume its a pseudo code
but basically the recv is not guaranteed to actually return anything immediately
thats the whole point of web sockets really, you only get the data when the other peer decides to send it to you
do you have any other code
import asyncio
import websockets
import re
async def main():
uri = f'wss://strangermeetup.com/socket.io/?lang=en&userId=413fcf79-3837-4608-b29d-ace29f84d3fe&client=web&EIO=3&transport=websocket&sid='
async with websockets.connect(uri=uri) as websocket:
msg = await websocket.recv()
rec_msg = re.findall('sid":"(.*?)"', msg)[0]
async with websockets.connect(uri=f'wss://strangermeetup.com/socket.io/?lang=en&userId=413fcf79-3837-4608-b29d-ace29f84d3fe&client=web&EIO=3&transport=websocket&sid=' + rec_msg) as websocket2:
await websocket2.send('2probe')
print(await websocket2.recv())
await websocket2.send('5')
print(await websocket2.recv())
asyncio.get_event_loop().run_until_complete(main())
i also tried with headers and stuff but nothing seems to work
no my friend was so happy that he has my ip ,
!paste
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.pydis.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.
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
are you basing that code off of any api or documentation? Do you absolutely have to connect to the same websocket the second time while being connected to it already (inside of async with context)
try:
u = urllib3.urlopen(url)
data = u.read()
except urllib3.HTTPError, error:
contents = error.read()
if "country_code" not in data:
# Couldn't fetch IP Information properly!
print "Couldn't retrieve your requested IP. Information properly!"
else:
Hey guy i got this code with me with urllib3 but when i run it i get this ssyntax error
except urllib3.HTTPError,error:
^
SyntaxError: invalid syntax
except Exception as exception
@ember ledge the first time when i connect i get the id, the second time i use that id to connect
i get the id - can you get it and then exit out of the current websocket connection?
how else would i get the id tho?
cause its different each time
async def main():
async with websockets.connect(uri=uri) as websocket:
msg = await websocket.recv()
rec_msg = re.findall('sid":"(.*?)"', msg)[0]
async with websockets.connect(uri=f'wss://strangermeetup.com/socket.io/?lang=en&userId=413fcf79-3837-4608-b29d-ace29f84d3fe&client=web&EIO=3&transport=websocket&sid=' + rec_msg) as websocket2:
await websocket2.send('2probe')
print(await websocket2.recv())
await websocket2.send('5')
print(await websocket2.recv())
asyncio.get_event_loop().run_until_complete(main())
?
Hi all, I thought this might be an appropriate place to share https://github.com/codemation/easyrpc, a project that I have been maintaining which IMHO makes in tremendously easy to network python processes together, which I have personally created a whole range of projects off of so far... Hope it might help to solve some of your problems too, but feel free to PM me if you have any questions.
how can i make the program to recieve and send users input (the guy that is in the server side) and recieve data being sent from a client ?
CompTIA worth getting?
I heard that the more certs you get
the more you make
but idk
okay guys, who here knows enough about sockets to tell me why the port I am running my service off of won't open on my digitalocean server?
check pinned
@ionic gate you would need to use .recv() and .send() to send and recieve data from server to client and remember to decode and encode the messages when they are sent
and remember to decode and encode the messages when they are sent
if necessary*
is it possible to send requests with sockets, asyncio and aiohttp? or just one of them
Yes, a request looks something like this
GET / HTTP/1.1
Host: target-site
User-Agent: Browser-name
Accept: text/html
Send a message like that to the server, and you will recv a response
It's possible with either aiohttp or requests.
you can send requests with either of them?
what is your question
I had VPS
First of all I think you might be misunderstanding what a socket is, a socket is an endpoint for sending and receiving data over a network, this could mean anything from HTTP to Bluetooth. A socket could send something immediately, 5 hours later, or never, this means an application must wait for the socket to have some data by waiting (blocking) or notifying in some fashion. Notifying is generally preferred for an application that has to handle a lot of sockets so they don't have to spawn 100's threads who spend most of their time waiting instead the application would wait for any of the sockets to be ready then notify something in some way when it is. Python provides something like this with the asyncio module, it polls multiple fds with select (selector event loops at least) and calls a function when the fd is readable/writable. This means you can use a Future to essentially notify a task when a socket is readable/writable. aiohttp uses asyncio to wait for sockets to be readable/writable so no you can't use aiohttp without asyncio. You can read from and write to sockets without asyncio but if you want it to notify instead of block you would have to make your own loop similar to asyncio's.
hey I don't know if this is the right place to ask this, but I'm trying to send video feed (or at least regular still images from it) from a phone camera to a python script on my desktop. Is this feasible or would I be better off getting my phone to run python?
idk if you can run python on a phone
but you can use an rpi and a camera using opencv
i'm not sure how
but look up "send video feed to device python opencv"
ports receives sockets, then?
Hey,
I have a quesiton, If you connect 2 devices on a common hotspot, does the data go through the hotspot and back to the other device ?
Yes, packets will be send throughout the gateway for both devices
So the packets are always going through the gateway and not directly from one device to the other ?
Exactly, until devices are not connected directly all packets go through gateway
When you say directly connected, you mean that one is as an access point ?
You can use ethernet cable
Your welcome
There are protocols that have ports (like TCP, UDP) but some protocols don't have ports (ICMP?)
ICMP isn't a protocol on the network layer.
How about Wiki? https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol
The Internet Control Message Protocol (ICMP) is a supporting protocol in the Internet protocol suite. It is used by network devices, including routers, to send error messages and operational information indicating success or failure when communicating with another IP address, for example, an error is indicated when a requested service is not ava...
OSI layer Network layer
oh wait ye i'm dumb i forgot a layer
TCP and UDP aren't in that layer then
they're in the transport layer
also I don't think TCP and UDP have ports
i learned the five layers model and only the application layer protocols have ports
UDP has source and destination port fields https://en.wikipedia.org/wiki/User_Datagram_Protocol#UDP_datagram_structure
In computer networking, the User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network. Prio...
that's not the own protocol's port
it specifies the port of the application layer's protocol
the port corresponds to the application layer's protocol in use
UDP datagrams literally have the ports as the first 32 bits
Hi guys I want to learn netowrking?
Oh, okay... I didn't get what you mean
the guy has no clue, ports are only a concept for TCP/UDP, not higher level protocols
I suppose that he was thinking about protocols like DNS - which HAS its dedicated port
Start with learning what is Ethernet frame and IPv4
Then UDP/ICMP ping messages, later go to TCP
that's just convention, it's not something built into the network stack (like actual dedicated source/destination port bytes for UDP/TCP)
Right 🙂
I have got a lot of experience with python but none with networking can someone pls guide me on how do I do this
do what?
Hey friends of Python. I have a project and want to implement VoIP into it. The program should make a phone call over the Fritz!Box. The Virtual Phone exists already , but I'm trying to get a Python Package which is able to call over the Network. Can anybody give me a clue of a working pack? Thanks
sockets. sockets are everything. i think 
How can i pass authentication in wss2 using websockets..... Wanna send message through it, but that site requires user authentication?
does anyone know how UDP can be used to create a ping with raw sockets?
built one using ICMP
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
but I want to also use UDP with it as well
#🤡help-banana for a networking related help thanks
👍
Hello @sand perch and @ember ledge, please don't post random memes here please
what are some of the best modoules for network automation?
What do you mean network automation?
Hey everyone! I'm interested in people looking at my code and telling me it's awful and possibly how I can make it better.. Both constructive and nonconstructive criticism is welcomed!
from netaddr import *
def macDialect(macAddr,macFormat):
lowerMacAddr = macFormat.lower()
mac = EUI(macAddr)
try:
if lowerMacAddr == 'unix':
mac.dialect = mac_unix
return(mac)
elif lowerMacAddr == 'juniper':
mac.dialect = mac_unix_expanded
return(mac)
elif lowerMacAddr == 'cisco':
mac.dialect = mac_cisco
return(mac)
elif lowerMacAddr == 'bare':
mac.dialect = mac_bare
return(mac)
except:
return('The provided mac address or format was invalid.')
if __name__ == "__main__":
mac = macDialect('00-1B-77-49-54-FD', 'juniper')
print(mac)
I'm new to python and programming in general. I am doing camelCase because honestly... I saw another programmer doing it. Is there any reading I can do to form a good habit instead of a bad habit when it comes to formatting my code's upper/lowercase?
snake_case
its the python convention
and imo it looks better
for other python style rules checkout
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
You can find the PEP 8 document here.
Also with the dict lookup, I think you're suggesting I treat the macAddr & macFormat as a single dict. I'll go ahead and make that change and test it out. It doesn't bother me now but my mindset is just to do some python every day. I bet when I start building code that depends on this I will form my own opinion/preference and a dict may be the better option.
building on what others have mentioned
- even if you don't use a dict, you can put the
return(mac)at the end of your if statements
also return isn't a function, it's normally just return mac
Not sure what you mean by placing return at the end of my if statements. Like this?
if lowerMacAddr == 'unix':
mac.dialect = mac_unix
return mac
elif lowerMacAddr == 'juniper':
mac.dialect = mac_unix_expanded
return mac
elif lowerMacAddr == 'cisco':
mac.dialect = mac_cisco
return mac
elif lowerMacAddr == 'bare':
mac.dialect = mac_bare
return mac
or to prevent so much repeating of myself maybe this?
if lowerMacAddr == 'unix':
mac.dialect = mac_unix
elif lowerMacAddr == 'juniper':
mac.dialect = mac_unix_expanded
elif lowerMacAddr == 'cisco':
mac.dialect = mac_cisco
elif lowerMacAddr == 'bare':
mac.dialect = mac_bare
return mac
what is mac in your code?
Where should I put my sqlite database for a Flask/Quart application?
Does anyone know a good alternative to pyaudio? Pyaudio is too laggy for me and the quality isnt perfect
Im working on a VC with the Focus on audiophile sound quality for free
In dc e.g. you have ti pay 30 boosts fir good quality
My vc already supports channels and servers but the quality isnt perfect, it uses pyaudio
Its 100% python made
laggy how
like the audio is a) pretty delayed but b) also like crazy cut off etc.
just sounds weird in between
crazy cut off?
you mean like high/lowpassed?
or stuttery
i wrote a voice call app a while ago and i'm pretty sure i just read bytes from the audio buffer and wrote them to a socket and vice versa
Hi! I'd like to implement a basic p2p network in python, but I have no idea where to start.. I have a basic understanding what a p2p network is but I wouldn't be able to get into deep details. Do you have any source or something like that? 🙂
(I know I have to learn networking, but that's everything but specific 😄 )
(sorry for the newbie question, :/ )
@deep portal http://cs.berry.edu/~nhamid/p2p/ this seems good here
Thank you! Did you use this source too?
Yo guys I have a ton of experience with python but none with networking and I have made a simple TCP chatroom, after I send one message an error occurrs stating "the host machine has aborted the connection"
And no firewall window Is popping
I am on windows
Are both the server.py and client.py on same network?
Yes
host_ip = "0.0.0.0" #or "127.0.0.1"
host_port = port_here
client_ip = "host_ipv4" #open cmd -> ipconfig -> You'll get your network IPV4 there
client_port = same_port_here
Where did u learn socket programming
?
two months ago I was in same scenario as in you are , I was confused like you but @prisma cobalt helped me
btw did that help @late kestrel
Got to try it , still thnx in advance
How, u just approached to him and asked ?
Nah, I was stuck somewhere so I posted my query here and he helped me
Though there are tons of freely available resources on youtube, you can check them out
k
Is there any platform to host server.py 24x7?
anyone have any good books on python networking
:)
😉
is this a discord bot or a web server?
I got my question answered in #python-discussion it's a chat room server
I would also like to know the same thing
def listener():
global conn, addr
while True:
conn, addr = s.accept()
clients.append(conn)
print(addr[0] + " connected!")
def receiver():
while True:
if not clients:
while True:
if clients: # wait until joins
break
# get every client response thing
for x in clients:
message = x.recv(1024).decode()
print(message)
any ideas how do i get every client response at the same time?
No offence but that’s not a good way of handling clients
Can u pls suggest a safe and a good way to handle cliets
can anyone suggest me best method to learn python scripting
code -> debug -> stack-overflow - eat -> sleep -> repeat until expert
I feel like this channel is lacking an example of a client-server program. I've taught about 4 people in the last week and I think it would be beneficial to have a properly annotated example for beginner introduction to sockets. So I will create a good example that hopefully a mod or helper pins to this channel as a resource for networking beginners
Hi everyone!
This is a simple example of a client-server program designed to help those who are struggling or provide an example to those interested in networking:
Simple client-server program using sockets + socket docs link:
https://docs.python.org/3/library/socket.html#example
if your using the first example yourself, remember to change the HOST variable in the client script to the IP of the server.
For learning the low levels of networking I would recommend realpython's tutorial:
https://realpython.com/python-sockets/
As an example of real world use, the following is code for a TCP chatroom by NeuralNine:
NeuralNine's video: https://youtu.be/3UOyky9sEQY
NeuralNine's advanced TCP chatroom (continuation): https://youtu.be/F_JDA96AdEI
nice, got the first human pin on this channel
Thnx man
no problem, happy to help 😊
Yo, I have a question
When u request an html page per exemple, your machine which is connected to network send a request but how he can find the associated server with URL ?
I guess there is not central switch which is link to every server.
welcome to DNS
you can see in this example "www.google.com"'s address actually has an IP of "172.217.169.4"
@prisma cobalt oh thx
then, how our machine can find the "ip" of google, Internet is big
find the IP of a website or your own machines public/private IP?
when you go to google.com, your browser:
- looks up google.com in a "domain name server", which basically tells it what the IP of google.com is
- connects to this IP, and the packets are routed to google via the internet
- google sends a response to your IP address, which your router knows, and this packet gets routed back through the internet
- your browser receives the packet and displays the webpage
there are a few more steps but this is basically how it works

for the example you asked (google) it actually has quite a few ips but thats advanced stuff lmao
so internet is only electromagnetic waves ?
no not at all
there are miles of fibre optic wires below the oceans as an example that transmit data between continents
thats considered the hardware of the internet
yeah i know about copper wires :p
Thank u guys, i see clearly now 🙂
because i was intrigued to know if someday, there was only one wire and 2 machines (how was the beginning of internet)
well if you think about it:
the inside of your machine is just components connected by cables
and yeah i guess at one point the internet was 2 computers connected by copper cable lmao
it's more Surface Mounted Device components than cables hehe
how do people send packets to routers with python
If your looking for a client-server script check out the channel pins, population by a message from yours truly
im like kinda new to this so idk what sockets are
You can send packets to routers but I feel like your asking how do you send packets to a computer on a network
what does that mean
Describe what your trying to do or imagining first
so i heard people saying that they made scripts to send packets to routers and i was wondering how that type of thing works
So your not actually trying to implement a python script? Your just wondering how it works
no i actually wanna know how to make a script cuz its better for me to understand
Okay there are two types of connection really:
A client-server network
A peer to peer network
The client server allows connections to a central server that manages everything for the clients
The peer to peer is limited but allows connections between computers without the need for a server
Game servers and message apps servers are server-client since the server handles the clients
Nearly everything you see is server client actually
oh that makes sense yea
what about the actual script on how people do this cuz it makes it so much easier to understan for me to actually see the code
Check out the pins (first link) for an example
Second link for a full explanation
oh ok thx
hi
what can i program in nerworking thats really cool?
TCP stack?
can i have a explaination on whats that'
Your custom implementation of TCP protocol - fragmentation, retransmission and so on
damn
is there a tutorial>?
I don't think so
Take proper RFC and go ahead!
Hey @radiant nymph!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
alright
If you want something easier you can implement IPIP tunneling for example
Ah , i'll do both
does
py charm work with js?
im so confused
I don't know, I am not JS developer
ah
i'll just try and find out
anyways
thanks for ur time ,its 1 am , gn
if anyone can answer my questions regurading networking like tcp and packets then dm me please the world of python networking is so confusing....
im learning scapy rn
What's your question?
If you think python networking is hard you should try a lower level language 😂
hi, if i wanted to make a application that was fully server sided and needed multiple connections to connect to it through telnet how would i do this
?
why does the second client not connect fully
?
Hm, it looks like that file might've been a virus. Instead of cooking up trouble, try cooking up a Chocolate Avocado Protein Smoothie: http://spinach4breakfast.com/chocolate-avocado-protein-smoothie/
bru no
lel the owner is network chunk
OMG
what?
check this out
yup
I have a problem
there is an http server:
with socketserver.TCPServer(("", PORT), PageHandler1.PageHandlerClass1) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
In PageHandlerClass1 (which is inherited from BaseHTTPRequestHandler):
def do_GET(self):
#parse parts of the request and make sure there are 4 of them
url = unquote(self.requestline)
url = url.replace(" ", "?")
url = url.replace("989", " ")
parts = url.split("?")
if len(parts) != 4:
print("Ignored request", parts)
self._set_headers()
encoded = bytes("Hi", "utf8")
self.wfile.write(encoded)
return
if len(parts) == 4:
print("Accepted request", parts)
#here I do the logic using parts
#... a lot of code
def do_POST(self):
try:
#parse parts of the request and make sure there are 4 of them
url = unquote(self.requestline)
url = url.replace(" ", "?")
parts = url.split("?")
if len(parts) == 4:
print("Accepted request", parts)
#here I do the logic using parts
#... a lot of code
except BaseException as e:
print("Exception", e)
The server works normally (and the web app is being used by a couple of my friends) but sometimes it just randomly "hangs" (doesn't respond to the client but the script is still working - looks like it's in the mid of request). It happens pretty rare, the server can work for days
In the logs I found this (the last thing before I had to restart it)
192.241.214.177 - - [23/Feb/2021 08:32:02] code 400, message Bad request version ('À\x14À')
192.241.214.177 - - [23/Feb/2021 08:32:02] " c]æBèðW%üy²îm.BêÍ
tevø;/
6Ë À/À+ÀÀÀÀ ÀÀ" 400 -
Any thoughts?
bad request...
The requests come from the JS client:
function ___api_get_root(port){
if(___debug){
return "http://localhost:"+port+"/api/"
}
else {
return "http://<my ip>:"+port+"/api/"
}
}
//for GET:
var req = new XMLHttpRequest();
req.open("GET", ___api_get_root(mainPort)+"article?lang="+std_langs[main_lang]+"&word="+repl, false);
req.onreadystatechange = function ()
{
...
}
req.send(null);
//for POST:
var rec = new XMLHttpRequest();
rec.open("POST", ___api_get_root(mainPort)+"linkify?align=0&lang="+std_langs[main_lang], true);
rec.onreadystatechange = function ()
{
...
}
rec.send(text);
I suspect this "bad request" comes from an outside place, not from my JS client
i cant help you there
https://www.abuseipdb.com/check/192.241.214.177
oh, and I found that this IP from the logs was reported for abuse 266 times
wait a minute...
ISP DigitalOcean LLC
that's where I host my app...
🤔
guys if i have a client that sends data to a server with a socket,
and i want the client to sometimes send messages like "switch channel" or stuff like that in between.
should i make a seperate socket for the messages? or mix the data socket with the messages???
the server offeres a socket for audio data, and the client sends this data
i also want the client to send messages in between, should i do a second scoket for that? or is that not the usual way to do it?
running the server in this way really isn't production ready
if you're expecting actual web traffic
any bad request will tie up the only serving thread and prevent others from connecting
@storm saffron
tnx 🙂
how to run a server in a "production ready" way?
well if you want to prevent the threading problem you can use ThreadingHTTPServer
oh you're using tcpserver
why
is it just for the experience of writing a socket http server?
tbh, I just google for "basic http server", and used the example code. I had no experience with that before. I was focused on the logic. It seemed to work so...
the logic was initially "just read the file and serve it back"
now there is a lot of complex logic there but I never really got into how the networking part operates
you shouldnt be using any of the inbuilt http stuff with python for prod
wow
that's a really big surprise for me
how it's normally done then?
well for serving files the standard case is using apache or nginx to serve that and then reverse proxy to something like gunicorn to run a WSGI framework
@gloomy root
tnx 🙂
hello
i really desperatly need your help, I want to make a get reuqest to REST API wordpress, and I get 401 error
So I have to authenticate somewhere, but I dont know where, what is the right way to do it..
can u help?
'
can somebody pls link me to a good socket programming course? im having a hard time finding one myself...
Check out this channels pins
k
Anytime someone asks about sockets I always direct them to the channels pins 😂 pure coincidence that a message from me is up there, pure coincidence indeed
well thats not answering my question tho
.
I never encountered a problem that may use 2 sockets before
okay, so if i try to use one socket, then how can i seperate messages from data?
because the socket obviously gets "spammed" with audio data, if i put a small socktet.send("switchroom") in between h?
wjere can i do lke stuff related to ip's in python
Can anyone help me understand restful api usage in Python? Trying to use an api but I'm lost 😭
Check out this project: "Netaddr" https://github.com/netaddr/netaddr
https://requests.readthedocs.io/en/master/ use this library
Practice against this https://httpbin.org/
Cheers man! That's what I'm using but there's some more information
thats very resourceful https://httpbin.org/#/Auth
could someone help me with a simple but annoying question on networking?
Don't ask to ask, what's up?
its a picture, you good if i dm it?
You can post it here, can't you?
oh right i havent been able to before
i wrote: "Using the subnet mask A = 131.21.3.0 B = 156.32.250.0 using an and gate adn the subnet mask."
I am not good with network addressing but in my opinion you should create two addresses - one in network 192.168.1.0 and another in 192.168.2.0
so you're identifying the private side of the routers interface so using the private ip?
According to the task's description - yes. But it's my opinion, I may be wrong
my dad agrees with you
but my friends dis agree
😂 im split between them
but yours and my dads explanation makes sense thank you!
Greetings for dad!
Your welcome
lol thank you
Discussion on network protocols, technologies, hardware with relation to Python
General discussion channel -> #python-discussion
should be able to i think
python on mobile tho... hmm
Hello i need some suggestions. I will need to connect few rpis with some kind of mesh connection in python (they will not be in same lan). I need to transfer files between them, send mesages (not broadcast) and also it would be great, that it would work even if some rpis crash. Thank you
I found this: https://p2p.today/python/tutorial/mesh.html But i am not exactly sure about files and also what if rpi, that i am connecting to crashes? And also for me it seems like communication is going through the "server" not p2p, or am i wrong
if you want to transfer files, ssh into the rpis and scp the files to wherever you want using the terminal
thats what i do
This is not what i want. I want to make python program, that would basically allow to send and request files from other rpis fully autonomously. Also as i said it needs to by something like mesh system and rpis will not be on the same LAN.
As i said, that module seems to solve my problem, but i am not sure, if it would handle file transfers (probably <250MB or even less, pics, text, maybe video) and i have feeling, that it is working through the "main" server and as i said mesh would be best solution for me (all devices can communicate with all other devices without help of server, server is not needed).
ok, make a python program, import os, use os module to run commands such as "scp {file} {user}:{ip} -P {port}"
hmmm... Ok thanks
the pis dont have to be on the same network
and then if you set up the program properly you can also send messages in files
if i would like to make a full application that uses telnet for useres to connect
how would ii manage multiiple connections directly to the telnet server
?
Im prob just being dumb but how do i fix this
Client shoudn't use connect?
Oh wait I figured it out I'm using .bind on the client program
