如何使用c#获取本地机器的ip地址? [英] How to get local machine ip address using c# ?

查看:89
本文介绍了如何使用c#获取本地机器的ip地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我想保存IP地址,如何点击我的网站,所以帮助我如何获得它。



我不希望服务器IP地址只是想要访问我网站的本地机器IP。



我尝试过:



我使用此代码



Hello All ,

I want to save the ip address how hits my site, so help me how to get it.

I don't want server IP address just want local machine IP which access my site.

What I have tried:

I Used this code

var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
        lblip.Text = ip.ToString() ;
        tblUserIP test = new tblUserIP();
        test.IPAddress = ip.ToString();
        test.UserID = LoginID;
        test.LoginTime = System.DateTime.Now;
        obj.tblUserIPs.Add(test);
    }







但是它给了服务器地址..




but it gives Server addres..

推荐答案

假设site是指一个ASP.NET站点,Request.UserHostAddress [ ^ ]是您正在寻找的属性。
Assuming by "site" you mean an ASP.NET site, Request.UserHostAddress[^] is the property you're looking for.


大家好,坦克为你的回复,我喜欢上述问题的解决方案

我用下面的代码为我工作



Hi All, Tanks for your reply,I fond the solution fro the above problem
I used below code and work for me

System.Web.HttpContext context = System.Web.HttpContext.Current;
           string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

           if (!string.IsNullOrEmpty(ipAddress))
           {
               string[] addresses = ipAddress.Split(',');
               if (addresses.Length != 0)
               {
                   return addresses[0];
               }
           }

           return context.Request.ServerVariables["REMOTE_ADDR"];






请点击以下链接。



获取本地IP地址



检查本地IP地址[C#]



谢谢,

Sisir Patro
Hi,

Follow the below link.

Obtaining local IP address

Check Local IP Address [C#]

Thanks,
Sisir Patro


这篇关于如何使用c#获取本地机器的ip地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆