[Tutor] python sockets

Alan Gauld alan.gauld at btinternet.com
Tue Jun 10 09:35:34 CEST 2014


On 10/06/14 00:33, Jon Engle wrote:
> I am trying to open ports 1025-65535 with the following code

Why would you want to do that?
It sounds like a great way to cripple your PC as it runs 64000 threads 
monitoring each of those ports. And it assumes that nothing else is 
using those ports already... And if you did find something trying to 
connect, what port is the server going to allocate? You've already 
grabbed them all?

Can you explain your rationale for trying to do this? Unless you are 
trying a brute force technique to prevent anything from connecting to 
your computer?

> found online with small modifications). I am unable to "bind" anything
> other than the one port which is selected as input. What am I missing
> and how do I bind all the ports simultaneously?

I think you are missing the basic concepts of server computing. You 
should never need to bind all the ports at once.

However as to your code... its hard to critique because you lost the 
indentation - presumably through posting in HTML? Try using plain text 
for posting code.

> #!/usr/bin/python           # This is server.py file
> from socket import *      #import the socket library
> import thread #import the thread library
>
> startingPort=input("\nPlease enter starting port: ")
> startingPort=int(startingPort)
>
> def setup():
...
> ## now we create a new socket object (serv)
> ## see the python docs for more information on the socket types/flags
> serv = socket( AF_INET,SOCK_STREAM)
> serv.bind((ADDR))
> serv.listen(5)    #5 is the maximum number of queued connections we'll allow
>
> serv = socket( AF_INET,SOCK_STREAM)
> serv.bind((ADDR))
> serv.listen(5)    #5 is the maximum number of queued connections we'll allow


Why do you do it twice?

> print 'listening...'

Is this Python 2 or 3? Your input lines above suggest its Python 3 but 
this print line suggests its Python 2. Which are you using?

> PORT=PORT+1
> conn,addr = serv.accept() #accept the connection
> print '...connected!'
> conn.send('TEST')
> conn.close()

You normally put the listening code inside a loop, waiting for a 
connection, processing it and then going back to listen some more....

> while startingPort<65535:
> thread.start_new_thread(setup())
> startingPort=startingPort+1

Minor niggle, if you must do this use a for loop. Its tidier.
As a minimum you need some error handling to deal with
unsuccessful attempts to bind. And you need a better way
of processing connections.

But fundamentally, I suspect that whatever you are trying to
do there is a better approach!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list