Showing posts with label mac. Show all posts
Showing posts with label mac. Show all posts

Wednesday, October 20, 2010

Python: Enumerating IP Addresses on MacOS X

How do you enumerate the host's local IP addresses from python? This turns out to be a surprisingly common question. Unfortunately, there is no pretty answer; it depends on the host operating system. On Windows, you can wrap the IP Helper GetIpAddrTable using ctypes. On modern Linux, *BSD, or MacOS X systems, you can wrap getifaddrs(). Neither is trivial, though, so I'll save those for a future post.

Luckily, MacOS X provides a simpler way to get the local IP addresses: the system configuration dynamic store. Using pyObjC, which comes pre-installed on every Mac, we can write a straight port of Apple's example in Technical Note TN1145 for retrieving a list of all IPv4 addresses assigned to local interfaces:

from SystemConfiguration import * # from pyObjC
import socket

def GetIPv4Addresses():
"""
Get all IPv4 addresses assigned to local interfaces.
Returns a generator object that produces information
about each IPv4 address present at the time that the
function was called.

For each IPv4 address, the returned generator yields
a tuple consisting of the interface name, address
family (always socket.AF_INET), the IP address, and
the netmask. The tuple elements may also be accessed
by the names: "ifname", "family", "address", and
"netmask".
"""
ds = SCDynamicStoreCreate(None, 'GetIPv4Addresses', None, None)
# Get all keys matching pattern State:/Network/Service/[^/]+/IPv4
pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(None,
kSCDynamicStoreDomainState,
kSCCompAnyRegex,
kSCEntNetIPv4)
patterns = CFArrayCreate(None, (pattern, ), 1, kCFTypeArrayCallBacks)
valueDict = SCDynamicStoreCopyMultiple(ds, None, patterns)

ipv4info = namedtuple('ipv4info', 'ifname family address netmask')

for serviceDict in valueDict.values():
ifname = serviceDict[u'InterfaceName']
for address, netmask in zip(serviceDict[u'Addresses'], serviceDict[u'SubnetMasks']):
yield ipv4info(ifname, socket.AF_INET, address, netmask)

One interesting point regarding this code is that it doesn't actually inspect interface information in the system configuration dynamic store. The interface-related keys are stored under State:/Network/Interface/, but this code (and Apple's example on which it is based) inspect keys under State:/Network/Service/ instead. However, if you want to get IPv6 addresses then you do have to inspect the system configuration's interface information:

from SystemConfiguration import * # from pyObjC
import socket
import re
ifnameExtractor = re.compile(r'/Interface/([^/]+)/')

def GetIPv6Addresses():
"""
Get all IPv6 addresses assigned to local interfaces.
Returns a generator object that produces information
about each IPv6 address present at the time that the
function was called.

For each IPv6 address, the returned generator yields
a tuple consisting of the interface name, address
family (always socket.AF_INET6), the IP address, and
the prefix length. The tuple elements may also be
accessed by the names: "ifname", "family", "address",
and "prefixlen".
"""
ds = SCDynamicStoreCreate(None, 'GetIPv6Addresses', None, None)
# Get all keys matching pattern State:/Network/Interface/[^/]+/IPv6
pattern = SCDynamicStoreKeyCreateNetworkInterfaceEntity(None,
kSCDynamicStoreDomainState,
kSCCompAnyRegex,
kSCEntNetIPv6)
patterns = CFArrayCreate(None, (pattern, ), 1, kCFTypeArrayCallBacks)
valueDict = SCDynamicStoreCopyMultiple(ds, None, patterns)

ipv6info = namedtuple('ipv6info', 'ifname family address prefixlen')

for key, ifDict in valueDict.items():
ifname = ifnameExtractor.search(key).group(1)
for address, prefixlen in zip(ifDict[u'Addresses'], ifDict[u'PrefixLength']):
yield ipv6info(ifname, socket.AF_INET6, address, prefixlen)

In fact, you could easily adapt the above function to be able to fetch IPv4 addresses from the interface configuration.

Monday, April 19, 2010

Good Day

All of our sea mail from Japan arrived and was just delivered. In addition, my new MacBook Pro I ordered last week (right after the revision bump) arrived today too. Looks like I'm going to be busy this week. I just hope I can find time to make it to BayPiggies this Thursday.

Wednesday, February 11, 2009

In Love with iTunes Movie Rentals

I've been meaning to try it for a while, but for the first time, on Tuesday night, we rented a movie from iTunes. Yet again, it was another impressively easy-to-use product from Apple.

Living in Japan, we often don't get movies for months after they come out in the states. And when they do finally come out here, they usually either dubbed into Japanese or have subtitles added. Frankly, dubbing sucks in more ways than I care to list. The subtitles aren't so bad, but they do detract from the movie a little. The most important selling point to us, though, is that we don't have to get dressed and walk 30+ minutes to the video rental store (and another 30+ minutes to return it when we're done).

So Tuesday night we basked in the warm glow of my wife's 24-inch iMac and watched WALL-E. Yes, not a new release, but I had only seen it on the airplane and my wife hadn't seen it all yet. It took all of 30 seconds to rent through the iTunes Store and the download began immediately.

On the downside, it took 2 hours to download the movie. While we could have started watching it immediately (while it continued to download in the background), since the movie was only about an hour and 20 minutes long, we didn't want to risk playback catching up to the download and ruining our movie-watching experience with "buffering" breaks. So, we watched a couple of episodes of The Daily Show online to let the download get a little over an hour head start.

With an hour left to finish downloading the movie, we started watching WALL-E full screen on the computer. The image quality was fabulous; there were no visible encoding artifacts at all. The sound was similarly superb. Even with the download continuing in the background, the movie played smooth with no hiccups. It was exactly what I would have expected from renting a title on physical HD-DVD or Blu-ray media.

Overall, the 1 hour lead time before we could start watching the movie was a little disappointing. But being able to sit comfortably at home and not hoof it down to the video store more than made up for that little setback. Next time, we'll probably either download the movie a day or two ahead of time or my wife will start the download when I leave the office so it is ready to play when I get home. Other than that, we were extremely pleased with the convenience, the quality, and the ease-of-purchase.

Apple nailed the user experience aspect again; there wasn't a single moment where I felt like we had to sacrifice something in order to gain convenience by purchasing online. The rental fee was commensurate: $4 to rent a recent release. I seem to recall Blockbuster charging $4-$5 to rent recent releases. So for roughly the same price as an old-school movie rental, I gained convenience but lost nothing. Even without our unusual circumstances, that looks like a decent deal to me.

So Apple iTunes' movie rental feature gets 4 thumbs up. As expatriates, we'll throw in 4 big-toes too, for a total of 8 digits up.

In case you are curious, there are services vaguely similar to NetFlix here, but they all require a) a Japanese credit card and b) postal delivery. I'll save my rant regarding trying to get a credit card in Japan for another day, but suffice to say we don't have one and aren't likely to get one during the remainder of our stay here.

Friday, August 17, 2007

Bought a Mac


My wife and I have been considering buying a new computer for a couple of months now; yesterday we bought a new 24" iMac. The odd thing is, even though my wife was comfortable on a Mac and I was drawn to the BSD underpinnings, we had decided against getting a Mac largely on the grounds of the expense (and the inability to easily uninstall software). Instead, we had settled on a small form-factor Dell. That is, until we visited the Apple Store on University Ave. Sunday afternoon.

We were in the neighborhood to pick up some prints at Wolf Camera and I wanted to stick my head in the Apple Store to check out the new Aluminum iMacs. They are gorgeous. I've never seen a screen quite like it. But the kicker was when my wife asked whether the $1799 price on the card next to the computer was for the computer we were looking at.

It wasn't. We were gawking at the 20" iMac; the placard was for the 24" iMac next to us. Now that was an impressive machine. And what was more amazing was that the $1799 price tag was on-par, if not cheaper, than the equivalent Dell desktop we had been considering! That's right, we could get the gorgeous iMac for the same price as the bland Dell we were planning to buy.

I have read claims in the past the recent-model Macs were cheaper than equivalent PCs, but there it was staring me in the face. Just to prove I'm not making this up, I just re-spec'ed the Dell machine we were going to buy to compare it to the Apple machine we did buy. As of 2007/08/17:

ComponentDell Optiplex 745 Small Form FactorApple iMac 24"
CPUIntel Core 2 Duo Processor E6600 (2.40GHz, 4M, 1066MHz FSB)Intel Core 2 Duo Processor T7700 (2.40GHz, 4M, 800MHz FSB)
OSWindows Vista Ultimate, with media, 32 Edition, EnglishMac OS X v10.4.10 Tiger
Memory1.0GB DDR2 Non-ECC SDRAM, 667MHz, (1DIMM)1.0GB DDR2 Non-ECC PC2-5300 SDRAM, 667MHz, (1SO-DIMM)
Hard Disk250GB SATA 3.0Gb/s320GB SATA 7200-rpm
Removable Disc8X Slimline DVD+/-RWSlot-loading 8x SuperDrive (DVD±R DL/DVD±RW/CD-RW)
Video Card256MB ATI Radeon X1300PRO256MB (GDDR3) ATI Radeon HD 2600 PRO
SpeakersDell™ A225 SpeakersBuilt-in stereo speakers
WiFiLinksys WUSB54GC Wireless-G USB AdapterAirPort Extreme wireless networking (802.11n)
Price w/o Monitor$1,198N/A
DisplayUltraSharp 2407WFP-HC 24-inch Widescreen Flat Panel LCD
$569
24-inch widescreen TFT active-matrix LCD
Total$1,767$1,799


Anyway, we left the Apple Store to head over to Fry's to do some shopping. But while we were at Fry's, my wife looked over at me and "we should get the Mac". She didn't have to say that twice. In my 15 years or so in the computer industry, I have never before seen a machine that I really wanted to buy. So we bought of copy of Parallels Desktop at Fry's and headed back over to the Apple Store.

Unfortunately, we were too late. They close at 6:00pm on Sundays. We tried again Monday night but both the University Ave. and Stanford Shopping Center stores were sold out of the 24" iMacs. We went ahead and ordered on on-line, but we were going to have to wait two weeks for it to even be shipped. So yesterday morning we made it up to the University Ave. store at 10:15am (they open at 10:00am) and bought the last 24" model in that day's shipment. That's right: sold out in 15 minutes. Needless to say, we cancelled our on-line order.

I was up to 4:00am last night setting up Parallels to run Win2k for some of our old software (namely, Microsoft Money and our favorite game: Settlers 3), installing Firefox and Thunderbird, importing our photos into iPhoto, etc. That screen is simply awesome. I don't think I've had this much fun since I was a kid. Certainly not with a computer.

Thursday, April 26, 2007

How I didn't buy a Mac

Before our move to Japan, my wife and I are considering buying a new, compact computer to take with us. Being the cool kids we are, we stopped by the local Apple Store to see if we liked anything. My wife worked in publishing for years and is pretty comfortable on a Mac; being a former FreeBSD developer, I liked the idea of BSD under the hood.

Anyway, we were pretty well sold on getting a Mac Mini until a thought crossed my mind: how do you uninstall software? I appreciate that Macs come with less circusware than Windows PCs, but when my "Test Drive" version of Microsoft Office or 30 day trial of iWork (sound familiar?) expires, how do I remove that useless trialware from my Mac?

We checked the help file on the Mac we were looking at -- there wasn't even an entry in the help addressing how to remove software. Not under "uninstall", not under "deinstall", or even "remove". In disbelief, we each took a turn visually scanning every single topic in the help file for something that even hinted at telling us how to uninstall a program. If there is an entry in the Mac help on removing software, we couldn't find it.

So we asked an employee. I wish I had a picture of the expression he made. Apparently it had never occurred to him you might ever want to remove software from a Mac. I guess that explains why Macs come with such large hard drives.

Experimenting, we tried just dragging an app into the trash to see if that would uninstall it. It worked: the app went into the trash. But I have no idea whether that meant the application was really uninstalled or not. Apparently, it depends on the app. And that is the answer that we (and the store employee we had baffled with the question) finally arrived at. Removing software on a Mac is really simple, unless it isn't.

On FreeBSD, I can pkg_delete programs I don't want anymore. On Windows they have an Add/Remove Programs item in the Control Panel that gets the job done pretty consistently. I'm sure linux has got the problem solved several different ways by now. I was honestly surprised that Apple didn't have a good, consistent solution for removing unwanted software. Perhaps the problem is too mundane?

I recall reading that retail stores' sales increase when shoppers know they can return goods without penalty. I think installing software is a lot like shopping: if I don't know whether I can remove it cleanly (i.e. without penalty) then I'm not likely to install it. Which means that I become really hesitant to install anything on my computer. If I can't comfortably try different editors, or mail readers, or web browsers, or whatever, then the value of the computer is appreciably reduced. For example, I know I would have never installed the FireBug add-on for Firefox had I not been sure I could remove the thing if it sucked (which it doesn't, by the way).

So we didn't buy a Mac. Yeah, I'm stupid, but that's the story: not being assured that we can cleanly uninstall software was enough that we left the store empty-handed. Perhaps we're more pragmatic than most. Perhaps I'm not as cool as I thought.