首页 > 代码库 > 13 在C#中如何获得IP地址
13 在C#中如何获得IP地址
首先需要添加命名空间
using System.Net.NetworkInformation; using System.Net.Sockets;
下面是详细代码
GetPrivateIP(); string publicIP = GetPublicIP(); Console.WriteLine("Public IP is: {0}", publicIP); //获取公共网络IP地址 static string GetPublicIP() { String address = ""; WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); using (WebResponse response = request.GetResponse()) using (StreamReader stream = new StreamReader(response.GetResponseStream())) { address = stream.ReadToEnd(); } // 从html页面中查找IP地址 int first = address.IndexOf("Address: ") + 9; int last = address.LastIndexOf("</body>"); address = address.Substring(first, last - first); return address; } //获取私有IP地址 static void GetPrivateIP() { foreach (var interfaces in NetworkInterface.GetAllNetworkInterfaces()) { foreach (var address in interfaces.GetIPProperties().UnicastAddresses) { if (address.Address.AddressFamily == AddressFamily.InterNetwork) { Console.WriteLine("IP Address: " + address.Address.ToString()); } } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。