• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#从远程服务器获得本机的上网ip

OC/C/C++ 水墨上仙 2506次浏览

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;
			}
		}
	}
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C#从远程服务器获得本机的上网ip
喜欢 (0)
加载中……