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

Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »

Price Scanner via MacPrices.net

Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.