[Tutor] Dodgey if loop ?

Lloyd Kvam pythonTutor at venix.com
Mon Sep 6 16:49:03 CEST 2004


Your for loop reads through the whole services file.  When p == pnumber,
you have found your match.  The else simply means you have not found
your match (yet).  The else is true for EVERY line except the line(s?)
that matches pnumber.

I think the rough pseudo code for what you want is:

for line in f:
	if <matches pnumber>: break
else:
	return '?'
return <services label>

This has the advantage of not reading the whole file for every pnumber.


You might be better off parsing the services file once into a dictionary
(or other map-like container), and then using pnumber to retrieve the
label for the port.



On Mon, 2004-09-06 at 10:25, nick at javacat.f2s.com wrote:
> Hi folks,
> 
> I've just wrote a little port scanner, and strangely enough I only have one
> problem with it lol .
> 
> Here's the offending code:
> 
> [code]
> pnumber = str(pnumber) #pnumber is 25 for example
> for line in f: # f is '/etc/services' open file
>     if not line.startswith('#') and len(line) > 10:
>         p = line.split()[1].split('/')[0]
>             if p == pnumber:
>                 return line.split()[0] # would return 'smtp'
>             #else:
>                 #return '?'
> [/code]
> 
> As it stands this works fine.
> However, if I uncomment the else loop in the final if loop it will always return
> the '?'. Leaving the final else commented out (as above) if pnumber is not in
> /etc/services it returns 'None' which I can live with.
> 
> Can anyone see why this is happening please ?
> 
> Here's a brief session of running the program with the final else commented out:
> [nickl at netview socket]$ ./scan.py bishop1 1 1024
> Trying bishop1 ...
> 
> bishop1 is listening on port 7 (echo)
> bishop1 is listening on port 9 (discard)
> bishop1 is listening on port 13 (daytime)
> bishop1 is listening on port 19 (chargen)
> bishop1 is listening on port 21 (ftp)
> bishop1 is listening on port 23 (telnet)
> bishop1 is listening on port 25 (smtp) ... etc
> 
> Here's what happens when I uncomment the final else:
> [nickl at netview socket]$ ./scan.py bishop1 1 1024
> Trying bishop1 ...
> 
> bishop1 is listening on port 7 (?)
> bishop1 is listening on port 9 (?)
> bishop1 is listening on port 13 (?)
> bishop1 is listening on port 19 (?)
> bishop1 is listening on port 21 (?)
> bishop1 is listening on port 23 (?)
> bishop1 is listening on port 25 (?) ... etc
> 
> Many thanks
> Nick.
> 
> 
> 
> 
> 
> 
> 
> 
>  
> -------------------------------------------------
> Everyone should have http://www.freedom2surf.net/
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	320-210-3409 (changed Aug 26, 2004)



More information about the Tutor mailing list