Archive for the ‘english’ Category

scanning for hosts on the local network

September 17th, 2006

One of the first things that pique my curiosity when I find myself in a new network environment is "what's around me?". To me it feels a bit like waking up from a dream and not remembering where I am or how I got there, so I want to look around a bit. I wrote a little script for this, and I can't say that it was terribly effective. It was based on using ping to send packets to every possible host on the current network (ie. the one I'm connected to presently). The scan was sequential, so it would ping 10.0.0.1, then ping 10.0.0.2 and so on. Most of these addresses had no hosts bound to them, so the scan would take forever for the ping to time out and move on to the next host. It would actually take so long (10min+) that in a wireless network, clients would come and go between the start and the end of the scan.

I didn't use ping because it was such a great choice for this problem, just that it was the first thing that occurred to me. I did get the script to run a bit faster by parallelling the pings, but this is a very silly thing to do, because with a Class C network, there are now 254 instances of ping running on the system. This would often drown out the packets from the hosts which were connected and the script would fail to report any hosts at all. I'm not sure why that is, but I improved the situation a bit by pausing for one second before starting every new thread.

Just the other day I stumbled upon a mention of using nmap to do this same thing. Sure enough, nmap was *designed* for this, so it should be the obvious choice. Somehow that never occurred to me. :lala: So I rewrote my little script to use nmap in place of ping. nmap does essentially the same thing as my script did, it pings hosts in parallell, but it does so without forking itself 254 times and it has some clever algorithms that monitor the state of the network to get best throughput at least congestion. To put that in plain English, here's a little comparison for a scan across 254 IP addresses:

  • parallell nmap: 0m 5.868s
  • parallell ping: 4m 15.912s

In other words, the ping method is absolutely rubbish. But, while I always have nmap available on my laptop, it's not an application that is installed by default on every system (unlike ping), so perhaps it would be handy to be able to fall back on the ping method, as lame as it is, if that's all we have.

Another small refinement is checking ifconfig for network info, so the user doesn't have to supply this manually. Again, this could fail (no priviliges, no ifconfig), so it's made to be an option, not a requirement.

#!/usr/bin/env python
#
# Author: Martin Matusiak <numerodix@gmail.com>
# Licensed under the GNU Public License, version 2.
#
# revision 2 - add hostname lookup


import os, string, re, sys, time, thread


def main():
	network = None
	try:
		netinfo = check_network()
		(ip, mask) = netinfo
		network = ip + "/" + mask
	except:
		print "Warning: No network connection found, scan may fail."

	if len(sys.argv) > 1:
		network = sys.argv[1]

	if not network:
		print "Error: No network range given."
		print "Usage:\t" + sys.argv[0] + " 10.0.0.0/24"
		sys.exit(1)


	if cmd_exists("nmap"):
		nmap_scan(network)
	else:
		print "Warning: nmap not found, falling back on failsafe ping scan method."
		ping_scan(network)


def nmap_scan(network):
	try:
		print "Using network: " + network
		cmd = 'nmap -n -sP -T4 ' + network + ' 2>&1'
		res = invoke(cmd)
		lines = res.split('\n')
		for i in lines:
			m = find('Host\s+\(?([0-9\.]+)\)?\s+appears to be up.', i)
			if m:
				print m, "\t", nslookup(m)
	except: pass


def ping_scan(network):
	iprange = find('(\w+\.\w+\.\w+)', network)
	print "Using network: " + iprange + ".0/24"
	for i in range(1,254):
		host = iprange + '.' + str(i)
		thread.start_new_thread(ping, (host, None))
		time.sleep(1)


def ping(host, dummy):
	try:
		cmd = 'ping -c3 -n -w300 ' + host + ' 2>&1'
		res = invoke(cmd)
		if "bytes from" in res: print host, "\t", nslookup(host)
	except: pass


def nslookup(ip):
	if cmd_exists("host"):
		cmd = 'host ' + ip + ' 2>&1'
		res = invoke(cmd)
		if "domain name pointer" in res:
			return res.split(" ")[4][:-2]
	return ""


def check_network():
	cmd = "/sbin/ifconfig"
	res = invoke(cmd)

	iface, ip, mask = None, None, None
	lines = res.split('\n')
	for i in lines:
		
		# find interface
		m = find('^(\w+)\s+', i)
		if m: iface = m
		
		# ignore loopback interface
		if iface and iface != "lo":
			
			# find ip address
			m = find('inet addr:([0-9\.]+)\s+', i)
			if m: ip = m
			
			# find net mask
			m = find('Mask:([0-9\.]+)$', i)
			if m: mask = m

	if ip and mask:
		mask = mask_numerical(mask)
		return (ip, mask)


def mask_numerical(mask):
	segs = find('(\w+)\.(\w+)\.(\w+)\.(\w+)', mask)
	mask = 0
	adds = (0, 128, 192, 224, 240, 248, 252, 254, 255)
	for i in segs:
		for j in range(0, len(adds)):
			if int(i) == adds[j]:
				mask += j
	return str( mask )


def find(needle, haystack):
	try:
		match = re.search(needle, haystack)
		if len(match.groups()) > 1:
			return match.groups()
		else: 
			return match.groups()[0]
	except: pass


def invoke(cmd):
	(sin, sout) = os.popen2(cmd)
	return sout.read()


def cmd_exists(cmd):
	if invoke("which " + cmd + " 2>&1").find("no " + cmd) == -1:
		return True
	return False



if __name__ == "__main__":
	main()

The output looks like this:

Using network: 192.168.2.119/24
192.168.2.1
192.168.2.119	james.home.lan

The first host listed, whose address ends in a 1, is often a router. Then there's the host transmitting the scan, that is localhost. At the time of the scan there were no other hosts connected on the network. Of course, beyond finding hosts, there's a lot more one can find out about them using.. *drumroll*.. nmap.

Update: I added a name lookup feature so that if there is a nameserver on the network, you not only get ip addresses, but hostnames as well. :)

why "how are you?" is pointless

September 16th, 2006

Some people who barely know me greet me with "how are you?". Now it's not that "how are you?" is a bad phrase, or a bad thing to say. Just that it's a filler for a situation that requires a sentence, without giving it any thought as to what you are saying. It's fine to say "how are you?" if you mean it. But otherwise it's pointless. And if you ask this person the same question "and you?", they won't say "oh today I'm excited cause I'm doing this" or "today I'm a little depressed cause I gotta do this". They just say "fine". So what's the point? Every time you ask the question, no matter how the person actually is, they will say "fine".

On the other hand, "what's up?" is just a little less pointless. The answer to "what's up?" is usually "oh nothing much", but there's a greater chance a person will tell you what they're doing than how they feel, because the latter is more personal. In fact, some people answer "what's up?" very sincerely, they will actually tell you.

Da Vinci Code: worth the wait

September 16th, 2006

I don't recall seeing one positive review of The Da Vinci Code. Which is why I didn't insist on seeing it as soon as it got out either. People have been trashing the story left and right, but I have to say I love this movie. The story (for the purpose of a movie anyway) is 'good enough', but beyond that it's such a cool theme, cool effects, lots of French and Latin, not too many obvious revelations. And Sophie, elle est trés sympa ;)

da_vinci_code.jpg

I had this imagine in my head of what the movie would be, and it isn't that at all. I can't quite say what it is that draws me to it, but watching it I felt like I was in a very special atmosphere, thoroughly enjoying the events rather than wanting to pick them apart. What I also found satisfying in the plot was that there literally was noone trustworthy, which makes a lot of sense. The historical references were cool and well placed.

Not forgetting the one very important factor contributing to this wonderful experience - the score. I've already heard it forwards and backwards basically, but to hear it in the movie is greatly satisfying, especially in the culmination point where we are treated to Chevaliers de Sangreal, a masterpiece. :star:

with time to spare

September 15th, 2006

Tennis is a funny sport. I've started playing recently, after a long, long break. I've never actually 'played it' in the proper sense of the term, never belonged to a club or anything like that. I used to play semi-regularly for a while as a kid, and it was fun. But tennis not being a popular sport in Norway (to put it mildly), I never took it any further. I guess I could have, but I preferred football and basketball. So now I live in Utrecht, there are plenty of courts in the student sports club and it's affordable.

But not having played for half a decade shows very well, I'm very awkward with tennis these days. The weirdest thing is having too much time. When there's a rather weak ball coming across, I have all the time in the world. I can chill for a while before I have to move into position. My technique, of course, is horrible, I need practice. But this period of 'free time' is very unsettling, it throws me off the rhythm. Just a moment ago I was in action hitting the ball, now I'm taking a break before the ball comes back. It's totally the kind of situation where I don't know if I should walk or run, I'm sorta on the fence about that decision. Tennis can be very dynamic, but it can also be very slow. And when you're not playing well, it's mostly slow. So I'm taking my time, I'm not rushing and I'm not getting the practice for using my time well. So when a fast ball comes at me, I can't cope with it, suddenly it's too fast. Not because I *couldn't* have reached it, but because I don't have the proper rhythm to react fast enough.

Interestingly, I don't play well under pressure. And in tennis there is no reward for a good performance overall, only the last ball counts. So even if I have a good exchange, I usually mess up the last ball and lose the point. Today I was taken to the cleaners, 6-0, 6-0. :D I didn't really feel up to playing a match, I'd rather just get more practice. Practice was going much better, much higher play to wait ratio. But sometimes you have to accommodate people.

Still, the biggest problem is finding people to play with. My tennis partner put up an ad to attract players and I responded to it. And apparently the other handful of people who did had no clue what they were doing, much worse than me even.

I would like to get a regular schedule going, but at the end of the day I'm still wondering if tennis is dynamic enough for me.

On the way home I stopped by these people who advertised they wanted to get rid of some tennis balls. Good lord did they hook me up, 4 boxes, 2 never even opened. Not only that, they wanted to give me a plastic bag full of old balls. All for just €3.5, which is a pretty damn good deal. I took the boxes, already a lot more balls than I need. They also had lots more golf balls, but I don't play golf. Super nice people too, Pakistani would be my guess. Apparently the husband used to play, but now they have a baby, so there's no time.

irregardless

September 13th, 2006

I love this word. I don't even remember where I saw it (it may have been some blog discussing language), but I feel a strong urge to use it. And I haven't found a context in which it would apply yet, but it's a wonderfully confusing word. It also sounds wonderful. Say it out loud to yourself, slowly, to really appreciate its elegance. :proud:

I received a letter today which contained the word irrespective and it immediately reminded me of a word I saw some time ago and wanted to use. It took me a while to remember irregardless, but now that I've blogged it, it's unlikely to escape me again. :cool:

Irregardless, one must do what one must, mustn't one?