您的位置:首页 > 编程语言 > ASP

ASP.NET获取IP及电脑名等信息的简单方法+通用类文件源码

2020-02-02 12:08 876 查看
1. 在ASP.NET 中专用属性:
获取服务器电脑名:Page.Server.ManchineName
获取用户信息:Page.User
获取客户端电脑名:Page.Request.UserHostName
获取客户端电脑IP:Page.Request.UserHostAddress

2. 在网络编程中的通用方法:
获取当前电脑名:static System.Net.Dns.GetHostName()
根据电脑名取出全部IP地址:static System.Net.Dns.Resolve(电脑名).AddressList
也可根据IP地址取出电脑名:static System.Net.Dns.Resolve(IP地址).HostName

3. 系统环境类的通用属性:
当前电脑名:static System.Environment.MachineName
当前电脑所属网域:static System.Environment.UserDomainName
当前电脑用户:static System.Environment.UserName


一个获取本机内网和外网IP的公用类 

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace ipip
{
 /// <summary>
 /// Class1 的摘要说明。
 /// 获取本机上网IP和内网IP
 /// </summary>
 public class Class1
 {
 
  private string strgetIP;
  
  public Class1()
  {
   //
  
  netIP();
  getIP(); 
  }
  
  
   
  

  public string renetIP()
  {return netIP();}//返回网络IP

  public string regetIP()
  {return strgetIP;}//返回内网IP

  
  static string netIP()
  {
   Uri uri = new Uri("http://www.ikaka.com/ip/index.asp");//查本机网络IP的网页
   HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
   req.Method = "POST";
   req.ContentType = "application/x-www-form-urlencoded";
   req.ContentLength = 0;
   req.CookieContainer = new CookieContainer();
   req.GetRequestStream().Write(new byte [0], 0, 0);
   HttpWebResponse res = (HttpWebResponse)(req.GetResponse());
   StreamReader rs = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("GB18030"));
   string s = rs.ReadToEnd();
   rs.Close();
   req.Abort();
   res.Close();
   Match m = Regex.Match(s, @"IP:\[(?<IP>[0-9\.]*)\]");
   if (m.Success) return m.Groups["IP"].Value;
   string strnetIP= string.Empty;
   return strnetIP;
  }

  public string getIP()//注意与static 的区别
  {
   System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;//获取本机内网IP
  

    strgetIP = addressList[0].ToString();
    return strgetIP;
   
  }

  
 
 }

}

转载于:https://www.cnblogs.com/cnmawei/archive/2007/01/15/620808.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
acli512345 发布了0 篇原创文章 · 获赞 0 · 访问量 288 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: