C# 取得内网IP、外网IP、客户端IP方法

 

前言

  在 Windows Form Application 里对于取得 IP Address 有内网、外网两种 IP Address ,如果只需要取得内网 IP Address ,可以透过使用 IPHostEntry 类别取得,而外网的话就必须要发送一个 Request 到一个可以取得 IP Address 的网站后再分析 Response 的内容,这个网站可以自己做或者使用现成的,如 http://www.whatismyip.com.tw/ 。

  另外,在使用 Socket 通讯的情况下,也有可能有需要知道前来连结的客户端的 IP Address 是什么,这时就可以使用 Socket.RemoteEndPoint 属性来取得远程 IP 地址和通讯端口编号,以下就列出范例代码看看该如何使用。

范例程序代码

/// <summary>
        /// 取得外网 IP Address
        /// </summary>
        /// <returns></returns>
        private string GetExtranetIPAddress()
        {
            HttpWebRequest request = HttpWebRequest.Create("http://www.whatismyip.com.tw") as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0";
            string ip = string.Empty;
            WebResponse response = request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string result = reader.ReadToEnd();
                string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
                ip = Regex.Match(result, pattern).ToString();
            }
            return ip; // result: 210.125.21.xxx
        }
取得外网 IP Address
/// <summary>
        /// 取得本机 IP Address
        /// </summary>
        /// <returns></returns>
        private List<string> GetHostIPAddress()
        {
            List<string> lstIPAddress = new List<string>();
            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ipa in IpEntry.AddressList)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                    lstIPAddress.Add(ipa.ToString());
            }
            return lstIPAddress; // result: 192.168.1.17 ......
        }
取得本机 IP Address

 

private static string GetIP()
{
    string tempip = "";
    try
    {
        WebRequest wr = WebRequest.Create("http://www.ip138.com/ips138.asp");
        Stream s = wr.GetResponse().GetResponseStream();
        StreamReader sr = new StreamReader(s, Encoding.Default);
        string all = sr.ReadToEnd(); //读取网站的数据

        int start = all.IndexOf("您的IP地址是:[") + 9;
        int end = all.IndexOf("]", start);
        tempip = all.Substring(start, end - start);
        sr.Close();
        s.Close();
    }
    catch
    {
    }
    return tempip;
}
取得外网ip

 

 

 

/// <summary>
/// 执行服务器监听
/// </summary>
public static void RunServer() 
{

    // 建立X509凭证
    ServerCertificate = new X509Certificate(Certificate, "ssl");
    // 监听任何IP Address来的讯息
    listener = new TcpListener(System.Net.IPAddress.Any, 17170);
    // 开启监听
    listener.Start();

    while (IsRun)
    {
        TcpClient client = listener.AcceptTcpClient();

        ProcessClient(client);
    }
}

/// <summary>
/// 接收客户端讯息处理并回复
/// </summary>
/// <param name="pClient"></param>
private static void ProcessClient(TcpClient pClient)
{
    SslStream sslStream = new SslStream(pClient.GetStream(), true);

    // 取得连接者 IP 与 Port
    IPEndPoint point = pClient.Client.RemoteEndPoint as IPEndPoint;
    string ip = point.Address.ToString(); // result: 127.0.0.1
    string port = point.Port.ToString(); // result: 55236

    // do something...
}
Socket 取得远程 IP Address 与 Port

 

string tempIP =string.Empty;if (System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.Length >1)     tempIP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[1].ToString();
如果是ADSL上网,获取公网ip

 

【ASP.NET开发】获取客户端IP地址 via C#

posted @ 2015-05-15 16:31  无恨星晨  阅读(9613)  评论(0编辑  收藏  举报