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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.