0

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 am 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".

Community
  • 1
  • 1
Manoj S Pant
  • 85
  • 2
  • 12
  • Sound like a homework question. – Wildhorn Aug 25 '10 at 18:15
  • Possible duplicate of http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c – Robb Aug 25 '10 at 18:16
  • Dupe http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c – Keith Adler Aug 25 '10 at 18:16
  • 1
    @Wild, really? I don't think so... – jjnguy Aug 25 '10 at 18:18
  • School started this or last week, and this is the kind of question students are asked to answer. – Wildhorn Aug 25 '10 at 18:33
  • Repoen: This isn't a fair close. The OP is clearly having an issue around one OS returning an IPV4 address and the other returning an IPV6 address. The "dupe" article does not go into any detail around this. The OP needs someone to explain the difference between AddressFamily.Internetwork and AddressFamily.InternetworkV6 - they don't need their question closed. – Rob Levine May 01 '11 at 14:48

2 Answers2

1

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;
kbrimington
  • 25,142
  • 5
  • 62
  • 74
-1

Here you go - quick google:

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

cristobalito
  • 4,192
  • 1
  • 29
  • 41