当前位置:编程学习 > C#/ASP.NET >>

C# 获取本机IP地址

怎么样获取C#的本机IP地址?



 IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
            string myip = IpEntry.AddressList[0].ToString();

这样,如果没有安装IPV6协议,可以取得IP地址.  但是如果安装了IPV6,就取得的是IPV6的IP地址.

string myip = IpEntry.AddressList[1].ToString();
这样就在IPV6的情况下取得IPV4的IP地址.

但是,如果本机有很多块网卡, 如何得到IpEntry.AddressList[多少]才是本机的局网IPV4地址呢?

--------------------编程问答-------------------- --------------------编程问答-------------------- 初学者  不会  O(∩_∩)O~   学习 !~!!~! --------------------编程问答-------------------- ding... --------------------编程问答-------------------- 路过,学习了!!~ --------------------编程问答-------------------- 其实你实现下就知道了。。 --------------------编程问答--------------------             IPHostEntry IPHost = Dns.Resolve(hostname);
            Console.WriteLine(IPHost.HostName);
            string []aliases = IPHost.Aliases; 

            IPAddress[] addr = IPHost.AddressList;
            Console.WriteLine(addr[0]);
  没记错的话是0 --------------------编程问答-------------------- 学习了 --------------------编程问答--------------------
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
namespace Network
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null) 
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
// 
// label1
// 
this.label1.Location = new System.Drawing.Point(32, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 16);
this.label1.TabIndex = 0;
this.label1.Text = "主机名:";
// 
// textBox1
// 
this.textBox1.Location = new System.Drawing.Point(96, 24);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(192, 21);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
// 
// label2
// 
this.label2.Location = new System.Drawing.Point(32, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 16);
this.label2.TabIndex = 2;
this.label2.Text = "IP地址:";
// 
// textBox2
// 
this.textBox2.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.textBox2.Location = new System.Drawing.Point(96, 56);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(192, 21);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "";
// 
// button1
// 
this.button1.Location = new System.Drawing.Point(64, 96);
this.button1.Name = "button1";
this.button1.TabIndex = 4;
this.button1.Text = "获取";
this.button1.Click += new System.EventHandler(this.button1_Click);
// 
// button2
// 
this.button2.Location = new System.Drawing.Point(184, 96);
this.button2.Name = "button2";
this.button2.TabIndex = 5;
this.button2.Text = "关闭";
this.button2.Click += new System.EventHandler(this.button2_Click);
// 
// Form1
// 
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(328, 142);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.MaximizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "演示获取主机名和IP地址";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() 
{
Application.Run(new Form1());
}

private void button2_Click(object sender, System.EventArgs e)
{//关闭程序
this.Close();
}
private void button1_Click(object sender, System.EventArgs e)
{//获取本机IP地址
   string HostName=Dns.GetHostName();
   this.textBox1.Text=HostName;
   IPHostEntry MyEntry=Dns.GetHostByName(Dns.GetHostName());
   IPAddress MyAddress=new IPAddress(MyEntry.AddressList[0].Address);
this.textBox2.Text=MyAddress.ToString();
}
}
}
--------------------编程问答-------------------- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
            ManagementObjectCollection nics = mc.GetInstances(); 
            foreach (ManagementObject nic in nics) 
            { 
                if (Convert.ToBoolean(nic["ipEnabled"]) == true) 
                { 
                    Console.WriteLine((nic["IPAddress"] as String[])[0]); 
   
                } 

            }
--------------------编程问答-------------------- winform的我不知道
webform的用
Request.ServerVariables["REMOTE_ADDR"]//客户端IP
--------------------编程问答--------------------   System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());


            for (int i = 0; i != IpEntry.AddressList.Length; i++)
            {
                if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                {
                    MessageBox.Show(IpEntry.AddressList[i].ToString());
                }
            } --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- 牛人 --------------------编程问答-------------------- 顶…… --------------------编程问答-------------------- 真的,倒没想过IPV6这个问题,提醒我了 --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- 学习 --------------------编程问答-------------------- IPAddress.AddressFamily 属性
对于 IPv4,返回 InterNetwork;对于 IPv6,返回 InterNetworkV6。
--------------------编程问答-------------------- 18楼正解,其他楼层都不对 --------------------编程问答-------------------- 过来学习 --------------------编程问答-------------------- 学习了 --------------------编程问答--------------------  /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetRealIP()
        {
            string ip;
            try
            {
                HttpRequest request = HttpContext.Current.Request;

                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
                }
                else
                {
                    ip = request.UserHostAddress;
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return ip;
        } --------------------编程问答--------------------
Up
引用 18 楼 bidisty 的回复:
IPAddress.AddressFamily 属性
对于 IPv4,返回 InterNetwork;对于 IPv6,返回 InterNetworkV6。
--------------------编程问答--------------------   学习了
  以前知道4的,没有研究过6的 --------------------编程问答-------------------- 同意通过AddressFamily 属性判断。

另外,本机ipv4也完全可能是多于1个地址的,不要以为只能有1个。 --------------------编程问答-------------------- --------------------编程问答-------------------- 学习了 --------------------编程问答-------------------- 汗,有这么复杂吗
using System.Net;

//方法一:

string strHostIP = "";
IPHostEntry oIPHost = Dns.Resolve(Environment.MachineName);
if (oIPHost.AddressList.Length > 0)
strHostIP = oIPHost.AddressList[0].ToString();

//方法二:
string ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();
--------------------编程问答-------------------- IPAddress.getHost()
的一些属性 可以得到 --------------------编程问答-------------------- using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Collections.Specialized;

namespace GetIpv4Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ShowIP();
        }
        void ShowIP()
        {
            //ipv4地址也可能不止一个
            foreach(string ip in GetLocalIpv4())
            {
                this.richTextBoxIPv4.AppendText(ip.ToString());
                }
            return;
        }
        string[] GetLocalIpv4()
        {
            //事先不知道ip的个数,数组长度未知,因此用StringCollection储存
            IPAddress[] localIPs;
            localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            StringCollection IpCollection = new StringCollection();
            foreach (IPAddress ip in localIPs)
            {
                //根据AddressFamily判断是否为ipv4,如果是InterNetWork则为ipv6
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    IpCollection.Add(ip.ToString());
            }
            string[] IpArray = new string[IpCollection.Count];
            IpCollection.CopyTo(IpArray, 0);
            return IpArray;
        }
    }
}
--------------------编程问答-------------------- 学习了,楼主加油。 --------------------编程问答-------------------- 学习了 --------------------编程问答-------------------- 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 --------------------编程问答-------------------- 学习……………… --------------------编程问答-------------------- mark --------------------编程问答-------------------- 路过,学习了~~~~顶顶顶 --------------------编程问答--------------------
引用 18 楼 bidisty 的回复:
IPAddress.AddressFamily 属性
对于 IPv4,返回 InterNetwork;对于 IPv6,返回 InterNetworkV6。



正解 --------------------编程问答-------------------- lai xue xi de  --------------------编程问答-------------------- 学习了 好东西 --------------------编程问答-------------------- 楼上的几种方法都行。 --------------------编程问答-------------------- Request.ServerVariables["SERVER_NAME"] 
呵呵,希望能帮到你! --------------------编程问答-------------------- 根据计算机名 获取ip地址,下面是代码: 
string hostName=Dns.GetHostName();
 this.txtName.Text=hostName;
 IPHostEntry Entry=Dns.GetHostByName(Dns.GetHostName());
 IPAddress pAddress=new IPAddress(Entry.AddressList[0].Address);
 this.txtIDAddress.Text=pAddress.ToString();
--------------------编程问答-------------------- dns类
其他的都是上面高手说的!
--------------------编程问答-------------------- 来顶顶~
学习了! --------------------编程问答-------------------- 楼上全有了 --------------------编程问答-------------------- 运行不起来啊 --------------------编程问答-------------------- 学习了 --------------------编程问答-------------------- 路过,学习了~~~~顶顶顶 --------------------编程问答-------------------- --------------------编程问答-------------------- 不知道是调用哪个类。。。
忘记了。。 --------------------编程问答-------------------- 输出的时候,把 地址类型==InterNetworkV6的不要显示就OK了....
声明和表达式:
IPAddress[] addr = ipEntry.AddressList;
addr[i].AddressFamily.ToString() != "InterNetworkV6"

--------------------编程问答-------------------- 学习了 --------------------编程问答-------------------- 用正则表达式把IPV6的地址过滤掉吧 --------------------编程问答-------------------- IPAddress.AddressFamily 属性
对于 IPv4,返回 InterNetwork;对于 IPv6,返回 InterNetworkV6。 --------------------编程问答-------------------- --------------------编程问答-------------------- 遍历每个网络接口
判断接口类型, 得到地址

类库中有的 --------------------编程问答-------------------- 标记一下。。 --------------------编程问答-------------------- [多杀] == 0 --------------------编程问答-------------------- 学习了 --------------------编程问答--------------------
引用 9 楼 wuyq11 的回复:
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
  ManagementObjectCollection nics = mc.GetInstances(); 
  foreach (ManagementObject nic in nics) 
  { 
  if (Convert……

+1
WMI做吧 --------------------编程问答-------------------- 在HttpRequest类里有个
string ip=Page.Request.UserHostAddress; --------------------编程问答-------------------- 考虑IPV4和IPV6的情况
private static string GetHostIP()
        {
            try
            {
                string hostname = Dns.GetHostName();
                System.Net.IPHostEntry ipEntry = Dns.GetHostEntry(hostname);
                if (ipEntry.AddressList.Length > 1) 
                {
                    string result = "255.255.255.255";
                    foreach (IPAddress ip in ipEntry.AddressList)
                    {
                        if (ip.ToString().Length < result.Length)
                        {
                            result = ip.ToString();
                        }
                    }
                    return result;
                }
                else
                {
                    return ipEntry.AddressList[0].ToString();
                }
            }
            catch(Exception ex)
            {
                throw new Exception("获取本机IP异常",ex);
            }
        } --------------------编程问答-------------------- 学习了... --------------------编程问答-------------------- using System.Net.Sockets;
using System.Net;


Dns.Resolve(Dns.GetHostName()).AddressList[0].ToString();  --------------------编程问答--------------------
引用 64 楼 c284980697 的回复:
using System.Net.Sockets;
using System.Net;


 label2.Text = Dns.Resolve(Dns.GetHostName()).AddressList[0].ToString(); 
--------------------编程问答-------------------- 没有什么好方法 --------------------编程问答-------------------- 获取本机正在使用的ipv4地址(访问互联网的IP),可别小看,还是有很多需要考虑的:
1.一个电脑有多个网卡,有线的、无线的、还有vmare虚拟的两个网卡。
2.就算只有一个网卡,但是该网卡配置了N个IP地址.其中还包括ipv6地址。

下面贴一个我一直使用的方法,它通过查询本机路由表,获取访问默认网关时使用的网卡IP。
用了2年了,屡试不爽。


      /// <summary>
        /// 获取当前使用的IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            string result = RunApp("route", "print",true);
            Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
            if (m.Success)
            {
                return m.Groups[2].Value;
            }
            else
            {
                try
                {
                    System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
                    c.Connect("www.baidu.com", 80);
                    string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                    c.Close();
                    return ip;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 获取本机主DNS
        /// </summary>
        /// <returns></returns>
        public static string GetPrimaryDNS()
        {
            string result = RunApp("nslookup", "",true);
            Match m = Regex.Match(result, @"\d+\.\d+\.\d+\.\d+");
            if (m.Success)
            {
                return m.Value;
            }
            else
            {
                return null;
            }
        }
 
        /// <summary>
        /// 运行一个控制台程序并返回其输出参数。
        /// </summary>
        /// <param name="filename">程序名</param>
        /// <param name="arguments">输入参数</param>
        /// <returns></returns>
        public static string RunApp(string filename, string arguments,bool recordLog)
        {
            try
            {
                if (recordLog)
                {
                    Trace.WriteLine(filename + " " + arguments);
                }
                Process proc = new Process();
                proc.StartInfo.FileName = filename;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.Arguments = arguments;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.UseShellExecute = false;
                proc.Start();

                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
                {
                    string txt = sr.ReadToEnd();
                    sr.Close();
                    if (recordLog)
                    {
                        Trace.WriteLine(txt);
                    }
                    if (!proc.HasExited)
                    {
                        proc.Kill();
                    }
                    return txt;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                return ex.Message;
            }
        }

--------------------编程问答-------------------- 呵呵… 学习 --------------------编程问答-------------------- --------------------编程问答-------------------- 不错,正好借用 --------------------编程问答-------------------- --------------------编程问答--------------------
引用 18 楼 bidisty 的回复:
IPAddress.AddressFamily 属性
对于 IPv4,返回 InterNetwork;对于 IPv6,返回 InterNetworkV6。


学习了 --------------------编程问答--------------------

System.Net.IPAddress ipaddress = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0];
ip = ipaddress.ToString();
--------------------编程问答-------------------- 这个很简单吧!!!
可惜书不在手边,忘了…… --------------------编程问答-------------------- 8楼正解~~~~ --------------------编程问答-------------------- 都是大牛啊!!8楼顶起!!! --------------------编程问答-------------------- Request.UserHostAddress.Tostring(); --------------------编程问答-------------------- --------------------编程问答-------------------- addreslist[0]是ipv6地址。
addreslist[1]是ipv4地址。
这是我得到的结果 --------------------编程问答-------------------- 大家用的是.NET什么版本的?

2.0尝试了下

AddressList.IsIPv6LinkLocal 判断下就好了 --------------------编程问答-------------------- foreach,就知道是哪个了 --------------------编程问答--------------------


 IPAddress _ip = IPAddress.Any;//获取本机IP


--------------------编程问答-------------------- 学些了!!! --------------------编程问答-------------------- 路过,学学! --------------------编程问答--------------------
引用 11 楼 zgke 的回复:
System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());


  for (int i = 0; i != IpEntry.AddressList.Length; i++)
  {
  if (!IpEntry.AddressList[i].IsIPv6LinkL……

正解! --------------------编程问答-------------------- 学习了, --------------------编程问答-------------------- 各种代码帝,果断要学习了。。。。 --------------------编程问答-------------------- 本机有多个网卡,那就意味着有多个IP地址。所以你无论获取哪一个,都是本机的地址。 --------------------编程问答--------------------  学习 学习 --------------------编程问答-------------------- 本机的Ipv4地址也可能不止一个啊?!你完全问的是个跑偏了的问题(没有搞清一个还是多个)。 --------------------编程问答-------------------- 应该可以更根据IP判断是IPV4还是IPV6吧! --------------------编程问答-------------------- System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());


  for (int i = 0; i != IpEntry.AddressList.Length; i++)
  {
  if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
  {
  MessageBox.Show(IpEntry.AddressList[i].ToString());
  }
  } --------------------编程问答-------------------- mark --------------------编程问答-------------------- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
ManagementObjectCollection nics = mc.GetInstances(); 
foreach (ManagementObject nic in nics) 

if (Convert…… --------------------编程问答-------------------- 顶你,言简意赅。 --------------------编程问答--------------------  学习了! --------------------编程问答-------------------- 学习了
楼上内容很齐全啊 --------------------编程问答-------------------- 路过,学习了!!~ --------------------编程问答-------------------- 本机IPv4地址本身就有多个,127.0.0.1可以过滤掉,如果排除127.0.0.1后只剩一个,就不需要这么麻烦了。
但如果还有多个其他IP地址,就要看应用了,如果是服务类型的,一般需要全部列出来让用户自己选择一个IP地址来监控。
如果是客户端应用,就要看路由记录了,如果在同一个网,还可以通过对方来提供反馈,例如一些网站就可以提供用户的访问IP查看功能。 --------------------编程问答-------------------- 学习了
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,