日期:2014-05-17  浏览次数:20484 次

.net获取外网IP
在网上找了很多都是这样的
C# code

 public string ResponseMyIP()
        {
                string str = null;
                //这个负责抓IP的页。第一步先抓取这个html页的全部内容
                string url = "http://www.ikaka.com/ip/index.asp";
                WebClient wc = new WebClient();
                wc.Credentials = CredentialCache.DefaultCredentials;
                Byte[] pageData = wc.DownloadData(url);
                string MyUrl = System.Text.Encoding.UTF8.GetString(pageData);
                //正则找到页面中的IP部分,并输出。
                Regex regex = new Regex(@"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))");
                foreach (Match m in regex.Matches(MyUrl))
                {
                    str = m.ToString();
                }
                return str;          
           
        }


有没有谁有不通过别人的网站来获取的代码啊!~~

------解决方案--------------------
C# code

string user_IP;
        if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
        {
            user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else
        {
            user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }

------解决方案--------------------
C# code
string qip = "";
            if (Request.ServerVariables["HTTP_VIA"] != null)
            {
                qip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                qip = Request.ServerVariables["ReMOTE_ADDR"].ToString();
            }

------解决方案--------------------
static string GetPage(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
try
{
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
catch (System.Exception e)
{
return e.Message;
}
finally
{
req.Abort();
}
}
// 通过外部网站得到本机的外部IP
static string GetOuterIP()
{
string patt = @"IP: \[(? <IP>[0-9\.]*)\]";
string url = "";
return Regex.Match(GetPage(url), patt).Groups["IP"].Value;
}

static void Main()
{
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
Console.WriteLine(ip);
}
Console.WriteLine();
Console.WriteLine(GetOuterIP());

 

------解决方案--------------------
你是想获取他所在的位置吧? 
/// <summary>
/// 获取指定URL页面的内容,使用HttpWebRequest方式
/// </summary>
/// <param name="xURL">URL的字符串表现形式</param>
/// <param name="encode">页面使用的编码</param>
/// <returns>返回页面HTML代码</returns>
public string Get_Page(string xURL)
{
string content = "";
HttpWebRequest httpget = (HttpWebRequest)HttpWebRequest.Create(xURL);
try
{
HttpWebResponse httpres = (HttpWebResponse)httpget.GetResponse();
Stream httpstr = httpres.GetResponseStream();
StreamReader sr