TweetFollow Us on Twitter

Serving From Home

Volume Number: 21 (2005)
Issue Number: 6
Column Tag: Programming

Serving From Home

Running A Mac Web Server With A Dynamic IPAddress

by Danny Swarzman

Introduction

With Mac OS X, the Macintosh has become an ideal platform for developing web applications. It includes an Apache server. All the services you want -- FTP, PHP, Perl, mySQL, Tomcat, etc. -- are either included with OS X or are available for free. You can test the client side on the same Macintosh that is running the server. You can edit web files with a regular text editor without an extra step to transfer them to a server.

Some accounts offered by Internet service providers don't offer all these services. Some accounts don't include access to the unix shell or don't allow you to view system log files- useful when you are debugging client-server communications. It would be helpful if you could use your home computer as a web server.

But there is a snag. A commercial Internet Service provides a static Internet Protocol address. When a user types an address into a browser, that address is sent to specialized servers on the Internet, Domain Name Servers. They locate the static IP address corresponding to the domain name.

If you are connected to the Internet via a cable or DSL service in your home, you don't have a static IP address. Instead, you have an address that can change every time you start you computer. It may even change while you computer is running. You can't have a domain name assigned to your home server.

This article shows a way that you can use a commercial Internet Service Provider account to act as your personal name server. The user enters the address of a web page on the commercial account. That page redirects the request to your home computer.

The load on the commercial server is very low. Once it's set up, you never need to change it. You may be able to use a friend's account. The only requirement for the commercial server is that it can run scripts in perl or some similar language. All the changes that you make on your site after that are on the home Macintosh.

The commercial server needs to know the Internet Protocol address currently assigned to your home computer. A script running periodically on home computer periodically sends a message to the commercial server to inform it of the home computer's address. `

The method has its drawbacks. I'm not suggesting this as a replacement for a static IP address for commercial or high volume applications. It is, however, handy for demonstrations and uses that don't demand 100% reliability.

Overview

The basic idea is very simple. This process uses two web servers: one on your Macintosh at home (hereafter called the Home Server), and a commercial server (hereafter called the Redirection Server). The Home Server periodically runs the script ip_to_server.pl. That script sends a request to the Redirection Server. The request contains the Home Server's IP address. The Redirection Server responds with the script ip_to_file.pl which saves the Home Server's IP address in a file. When a browser sends a request to the Redirection Server, the Redirection Server uses the saved IP address to redirect the client's request for a web page to the Home Server. (See Figure 1.)

For example suppose that the saved IP address is 92.2.92.2 and the address of the Redirection Server is http://stowlake.com/. The user enters or clicks on a link to:

http://stowlake.com/redirect.pl?xfile=some.html

The script redirect.pl redirects the request to the file specified by the xfile parameter on the Home Server:

http://92.2.92.2/some.html


Figure 1. Putting it all together.

This method has several limitations. First, of course, the Home Server needs to be turned on all the time that someone may want to access the pages involved. Also, there can be a lag between the change in the IP address on the Home Server and latest cycle of saving the IP address on the Redirection Server. When that happens, the client will fail to get the right page. The frequency with which a dynamic IP address changes depends upon the quality of the DSL connection. It can vary between several times per hour to several times a week. Do some experiments.

Configuring the Redirection Server

Let's get into specific details. First, let's see how to configure the Redirection Server. You can use any commercial Internet server that supports Perl or some other convenient language. Our examples are in Perl. One script stores the IP address of the Home Server. Another retrieves that address when it needs to redirect a request from the web client.

Remembering the Home Server's IP Address

In response to a request from the Home Server, the script ip_to_file.pl stores the address of the sender. Listing 1 shows this script.

Listing 1: Caching the Home Server's Address

ip_to_file.pl

#!/usr/bin/perl -w
# Save IP address received from Home Server to file.

use CGI qw(:standard);

$ipfile = 'home_server_ip';
print header,start_html;
if(open IPFILE, ">$ipfile")
{
   $ip = $ENV{REMOTE_ADDR};
   print IPFILE $ip."\n";
   close IPFILE;
   print "Wrote to file $ipfile: $ip";
}
else
{
   print "Failed to open file $ipfile for writing.";
}
print end_html;

This script is a CGI script that sends back a response that contains the IP address that it just saved.

Redirecting to the Home Server IP Address

The redirection script redirect.pl is shown in Listing 2. It takes a single parameter, 'xfile'. That is the filepath on the Home Server to which the request will be redirected.

Listing 2: Redirecting to the Home Server's address

redirect.pl

#!/usr/bin/perl -w
# Save IP received from Home Server.

use CGI qw(:standard);

# Redirect a request to the Home Server.
# The file to which to redirect is specified by parameter xfile.
# The IP address of the Home Server is retrieved from the file.

$ipfile = 'home_server_ip';
$fileOnHomeServer = param('xfile');

if(defined($fileOnHomeServer))
{
   if(open IPFILE, "<$ipfile")
   {
      chomp ($ip = <IPFILE>);
      print "Location: http://$ip/$fileOnHomeServer\n\n";
   }
   else
   {
      print header,start_html;
      print "Failed to open file $ipfile";
   }
}
else
{
   print header,start_html;
   print "Failed to retrieve file to access.";
   $fail=1;
}
print end_html;

Configuring the Home Server

The script in Listing 3, ip_to_server.pl, sends a request to ip_to_file.pl on the Redirection Server. The IP address of the sender is automatically sent with an HTTP request. There doesn't need to be any special code in ip_to_server.pl for that.

Listing 3: Sending an address to the Redirection Server

ip_to_server.pl

#!/usr/bin/perl -w

use LWP::UserAgent;
use HTTP::Request::Common qw(GET);

# Send a request to the Redirection Server to save this computer's IP
# 
# Server finds the IP in the request, saves it and returns 
# the IP in its response.
#
# This script records its transactions in a log file.
#
$kRedirectionServerAddress = 
   'http://www.stowlake.com/cgi-bin/ip_to_file.pl';	
open LOGFILE, ">>/tmp/ip_to_server.log" 
   or die "Couldn't open ip_to_server.log $!\n";
print LOGFILE scalar(localtime());
my $userAgent = new LWP::UserAgent;
my $request = GET $kRedirectionServerAddress;
my $response = $userAgent->request($request);
my $success = $response->is_success();
my $found = 0;
if( $success )
{
   my $content = $response->content;
   if ( $content )
   {
      my @data = split /\n/, $response->content;
      for(@data)
      {
         if(/Wrote to file/)
         {
            print LOGFILE "   ip was updated to: ";
            /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
            print LOGFILE $1."\n";
            $found = 1;
         }
      }
   }
}
else
{
   print LOGFILE "Failed to contact server: \n".
      $response->error_as_HTML."\n";
}
print LOGFILE "failed to update ip\n" if !$found;

Setting It Up

So we've got a couple of Perl scripts at hand. How do we set this thing in motion?

Upload Scripts to the Redirection Server

First, we need to upload the two scripts ip_to_file.pl and redirect.pl to the redirection server. Most ISP's allow you to upload files using the File Transfer Protocol (FTP). I typically use the application Fetch 4.0.3 to do this. You may of course prefer other tools.

Depending on your ISP, there may be a specific folder into which you put CGI scripts. For mine, cgi-bin is its name and it appears when I connect to their FTP site. Check with yours. They may set up the files differently. Whatever folder you use, you need to set the file permissions to allow execution of the scripts. In Fetch, use "Set Permissions..." in the Remote menu. Check the boxes as shown in Figure 2 for each of the Perl scripts.


Figure 2. Setting File Permissions

If you have access to the UNIX shell on your Redirection Server, you can set permissions with the shell commands:

chmod 755 ip_to_file.pl
chmod 755 redirect.pl

Once the files are in place, you can test them from a web browser. Enter the URL for ip_to_file. In my case, it's:

http://www.stowlake.com/ip_to_file.pl

A message with the IP address of your home Macintosh should appear in the browser window. Look for a file on your ISP site called home_server_ip. It should be in the same directory as ip_to_file.pl.

Start the Web Server on the Home Macintosh

Next we need to start the server on the home machine. Open the System Preferences application and choose the Sharing panel. Check the box labeled Personal Web Sharing, as in Figure 3.


Figure 3. Starting the Web Server

Put a sample web page into the directory /Library/WebServer/Documents on the boot drive. If you file is called some.html, type this into a web browser's address box:

http://localhost/some.html

If you see the page, your web server is running.

Run a Script on the Home Macintosh Periodically

The final piece of the puzzle is to run the ip_to_server.pl script on the Home Server. Modify the sample file to user your Redirection Server by changing the value of $kRedirectionServerAddress to the address of the directory on the Redirection Server that contains the scripts you put there. Put ip_to_server.pl in a convenient place on your Macintosh. I chose /Library/WebServer/CGI-Executables.

Make the script executable. Open the Terminal application. The Terminal application is in the Utilities subfolder of the Applications folder in the main drive. Go to the directory to where you put ip_to_server.pl and change the permissions. For example:

cd /Library/WebServer/CGI-Executables
chmod 755 ip_to_server.pl

Now try running the script. Just enter:

./ip_to_server.pl

You can tell if it worked with this command:

cat /tmp/ip_to_server.log

You should see a message in the terminal window telling you that the IP address was updated.

Finally, you need to get the script to run periodically, in my case every 10 minutes. You need to use the command, crontab, in the Terminal application. There is a program that is always running, the cron daemon. It periodically scans the table created by the crontab command. For each entry, if its time has come, cron calls the associated command. (You may want to review crontab documentation. Type "man crontab" into the Terminal application. Or, you can use the application ManOpen to view man pages.)

The first step is to create a file that specifies when ip_to_server.pl is to run. Let's call it ip_to_server.crontable. This example says: execute the specified command at 0 minutes, 10 minutes, ..., after the hour. Repeat every hour of every day of every month, including every day of the week. The contents of ip_to_server.crontable is this one line:

0,10,20,30,40,50 * * * * /Library/WebServer/CGI-Executables/ip_to_server.pl

Next enter a command in the terminal window:

sudo crontab -u username ip_to_server.crontable

(For username, substitute your login name on your Macintosh.)

Finally to verify:

crontab -l

The last command displays contents of the cron table just created.

Conclusion

Many of us may have thought that signing up for Internet services that use a dynamic IP address was thereby to give up any hope of serving web pages from our home computers. As I've shown in this article, a dynamic IP address is really no barrier to doing this. Rather, we simply need to upload a few simple Perl scripts to the Redirection Server and then periodically update the stored IP address by running a local cron job. As we've seen, this is not an industrial-strength solution, but it's probably fine for letting your relatives view photos from your recent trip to Hawaii or peruse your weblog. You need to experiment to know how it works for you.

References and Credits

ManOpen is a Macintosh application to easily view man pages. You can scroll through them, follow links from man page to man page and print man pages.

http://www.clindberg.org/projects/ManOpen.html

Bob Ackerman showed me how to do what I've described here. The sample code in this article was inspired by his example. He also reviewed this article. Thanks also to Victoria Leonard for her helpful suggestions and to Tim Monroe for his editing assistance.


Danny Swarzman writes programs in JavaScript, Java, C++ and other languages. He also plays Go and grows vegetables. You can contact him with comments and job offers at dannys@stowlake.com and http://www.stowlake.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.