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

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... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.