2010-08-25 45 views
0

可能重复:
How to get my own IP address in C#?如何在C#代码获取IP地址

我需要得到系统,其中应用程序是由C#代码

运行的IP地址
IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName()); 
foreach (IPAddress theaddress in ip) 
{ 
    String _ipAddress = theaddress.ToString(); 
} 

我正在使用此代码,但这是在不同的操作系统中给出不同的结果。例如,在Windows 7中,它提供了“fe80 :: e3:148d:6e5b:bcaa%14”
以及它给出“192.168.10.93”的Windows XP。

+0

听起来像一个家庭作业的问题。 – Wildhorn 2010-08-25 18:15:40

+0

可能的重复http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c – Robb 2010-08-25 18:16:29

+0

Dupe http://stackoverflow.com/questions/1069103/how-to -get-my-own-ip-address-in-c – 2010-08-25 18:16:51

回答

1

注意,你可能会被分配一台机器多个IP地址。你可以像这样检索它们(注:此代码忽略回送地址):用

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()); 
    } 

命名空间包括:

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