C#从远程服务器获得本机的上网ip
using System; using System.IO; using System.Net; using System.Text.RegularExpressions; namespace RobvanderWoude { class WANIP { static int Main( string[] args ) { // These are the URLs the program uses to try and get the computer's WAN IP address; if // a site fails, the next one is tried; if all fail, their error messages are displayed string[] urls = { "http://www.robvanderwoude.com/wanip.php", "http://www.robvanderwoude.net/wanip.php", "http://automation.whatismyip.com/n09230945.asp" }; if ( args.Length == 0 ) { bool found = false; string errMsg = string.Empty; string ipPattern = @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"; string myIP = string.Empty; WebClient myWebClient = new WebClient( ); foreach ( string url in urls ) { if ( !found ) { try { Stream myStream = myWebClient.OpenRead( url ); StreamReader myStreamReader = new StreamReader( myStream ); myIP = myStreamReader.ReadToEnd( ); if ( Regex.IsMatch( myIP, ipPattern ) ) { Console.WriteLine( myIP ); found = true; } else { errMsg = errMsg + "\n\nThe URL did not return a valid IP address: " + url; } } catch ( Exception e ) { errMsg = errMsg + "\n\n" + e.Message + " (" + url + ")"; } } } if ( found ) { return 0; } else { if ( !String.IsNullOrEmpty( errMsg ) ) { Console.Error.WriteLine( errMsg ); } return 1; } } else { Console.Error.WriteLine( ); Console.Error.WriteLine( "WANIP.exe, Version 1.02" ); Console.Error.WriteLine( "Return the computer's WAN IP address" ); Console.Error.WriteLine( ); Console.Error.WriteLine( "Usage: WANIP" ); Console.Error.WriteLine( ); Console.Error.WriteLine( "Note: The program tries " + urls.Length + " different URLs to get the WAN IP address" ); Console.Error.WriteLine( ); Console.Error.WriteLine( "Written by Rob van der Woude" ); Console.Error.WriteLine( "http://www.robvanderwoude.com" ); return 1; } } } }