-
-
Save Torxed/e6bf902aa86289b197b20607a9714d4a to your computer and use it in GitHub Desktop.
from socket import * | |
sockets = {} | |
s = socket() | |
s.bind(('', 1234)) | |
s.listen() | |
ns, na = s.accept() | |
sockets[na] = ns | |
if na in sockets: | |
sockets[na].close() |
BRAVO!!
(but I do think a gist can be a great mini guide or at least starting poitn for beginners, because search engines often think so too :D )
And bonus points for the better naming of the variables ~!
Of course much much more could be written because sockets are deep in any language.
(like 0.0.0.0 is IPv4 for localhost (and the rabbit hole gets deeper…)) (am I lisping here?)
BRAVO!!
(but I do think a gist can be a great mini guide or at least starting poitn for beginners, because search engines often think so too :D )
And bonus points for the better naming of the variables ~!
Of course much much more could be written because sockets are deep in any language.
(like 0.0.0.0 is IPv4 for localhost (and the rabbit hole gets deeper…)) (am I lisping here?)
Cheers :) Just a quick remark on that IPv4, 0.0.0.0
is actually not localhost.
0.0.0.0
is actually a non-routable IP, used as placeholder for various things.
Python automatically parse this nonsense IP as "all available IP's", and most kernels and services do too.
localhost
however (or 127.1
for short) is routable, and is an actual interface on most operating systems.
So binding to 127.1
will ensure that your socket is only accessible locally, where as 0.0.0.0
will let the socket be available to the world and localhost.
More on the topic on stackoverflow and on this random blog.
But yes, the rabbit hole is deep - and this is why gists can be a bit confusing for complex topics.
To better and fully understand them, there's many other examples. But this was a mini-example as you mentioned and gists are great for it.
Ps. Yea I was a bit ashamed of my lazy variable naming. Fell back to common annotations for ns
and na
because that's widely used. But that's no excuse, so re-wrote them heh.
True, the context was Five Python Features You (Probably) Didn’t Know. Of how you can use sets/lists/tuples as keys in a dictionary and why that might be useful.
Here's a comment version, altho a gist shouldn't a guide for beginners, or anyone. More functions as quick examples or a whiteboard to a broader conversation.