开发者

How to get an IP address in C# code [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How to get my own IP address in C#?

I need to get the IP address of the system, where the application is running by C# code

IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());   
foreach (IPAddress theaddress in ip)
{
    String _ipAddress = theaddress.ToString();
}

I a开发者_Python百科m using this code, but this is giving a different result in a different operating system. For example, in Windows 7 it is giving "fe80::e3:148d:6e5b:bcaa%14"

and Windows XP it is giving "192.168.10.93".


Note that you may have multiple IP addresses assigned to a machine. You can retrieve them like so (note: this code ignores the loopback address):

  var iplist = new List<string>();
  foreach (var iface in NetworkInterface.GetAllNetworkInterfaces())
  {
    var ips = iface.GetIPProperties().UnicastAddresses;
    foreach (var ip in ips)
      if (ip.Address.AddressFamily == AddressFamily.InterNetwork &&
          ip.Address.ToString() != "127.0.0.1")
        iplist.Add(ip.Address.ToString());
  }

Namespaces used include:

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;


Here you go - quick google:

http://msdn.microsoft.com/en-us/library/system.net.ipaddress(v=VS.100).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜