Powered by GeSHi

Source code for wanip.cs

(view source code of wanip.cs as plain text)

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text.RegularExpressions;
  5.  
  6. namespace RobvanderWoude
  7. {
  8. 	class WANIP
  9. 	{
  10. 		static int Main( string[] args )
  11. 		{
  12. 			// These are the URLs the program uses to try and get the computer's WAN IP address; if
  13. 			// a site fails, the next one is tried; if all fail, their error messages are displayed
  14. 			string[] urls = { "http://www.robvanderwoude.com/wanip.php", "http://www.robvanderwoude.net/wanip.php", "http://automation.whatismyip.com/n09230945.asp" };
  15.  
  16. 			if ( args.Length == 0 )
  17. 			{
  18. 				bool found = false;
  19. 				string errMsg = string.Empty;
  20. 				string ipPattern = @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$";
  21. 				string myIP = string.Empty;
  22. 				WebClient myWebClient = new WebClient( );
  23.  
  24. 				foreach ( string url in urls )
  25. 				{
  26. 					if ( !found )
  27. 					{
  28. 						try
  29. 						{
  30. 							Stream myStream = myWebClient.OpenRead( url );
  31. 							StreamReader myStreamReader = new StreamReader( myStream );
  32. 							myIP = myStreamReader.ReadToEnd( );
  33. 							if ( Regex.IsMatch( myIP, ipPattern ) )
  34. 							{
  35. 								Console.WriteLine( myIP );
  36. 								found = true;
  37. 							}
  38. 							else
  39. 							{
  40. 								errMsg = errMsg + "\n\nThe URL did not return a valid IP address: " + url;
  41. 							}
  42. 						}
  43. 						catch ( Exception e )
  44. 						{
  45. 							errMsg = errMsg + "\n\n" + e.Message + " (" + url + ")";
  46. 						}
  47. 					}
  48. 				}
  49. 				if ( found )
  50. 				{
  51. 					return 0;
  52. 				}
  53. 				else
  54. 				{
  55. 					if ( !String.IsNullOrEmpty( errMsg ) )
  56. 					{
  57. 						Console.Error.WriteLine( errMsg );
  58. 					}
  59. 					return 1;
  60. 				}
  61. 			}
  62. 			else
  63. 			{
  64. 				Console.Error.WriteLine( );
  65. 				Console.Error.WriteLine( "WANIP.exe,  Version 1.02" );
  66. 				Console.Error.WriteLine( "Return the computer's WAN IP address" );
  67. 				Console.Error.WriteLine( );
  68. 				Console.Error.WriteLine( "Usage:  WANIP" );
  69. 				Console.Error.WriteLine( );
  70. 				Console.Error.WriteLine( "Note:   The program tries " + urls.Length + " different URLs to get the WAN IP address" );
  71. 				Console.Error.WriteLine( );
  72. 				Console.Error.WriteLine( "Written by Rob van der Woude" );
  73. 				Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  74. 				return 1;
  75. 			}
  76. 		}
  77. 	}
  78. }
  79.