110,539
社区成员
发帖
与我相关
我的任务
分享
IPAddress localAddress = AddressHelper.GetLocalhostIPv4Addresses().First();
private IEnumerable<System.Net.IPAddress> GetIPs()
{
System.Net.IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());
return addressList.Where(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
//调用
foreach (var v in GetIPs())
{
Console.WriteLine(v);
}
Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString()
就这一行代码 简单残暴 public string GetLocalIP()
{
List<string> strIPs = new List<string>();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
var mac = adapter.GetPhysicalAddress(); Console.WriteLine(mac);
IPInterfaceProperties ip = adapter.GetIPProperties();
UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
foreach (UnicastIPAddressInformation ipadd in ipCollection)
{
//InterNetwork IPV4地址
//InterNetworkV6 IPV6地址
if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
{ //判断是否为ipv4
Console.WriteLine(ipadd.Address.ToString());
strIPs.Add(ipadd.Address.ToString());
}
}
}
}
return string.Join(";", strIPs);
}
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
用到的引用,已发表的不能编辑真是丹腾public string GetLocalIP()
{
//获取说有网卡信息
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
//判断是否为以太网卡
//Wireless80211 无线网卡 Ppp 宽带连接
//Ethernet 以太网卡
//这里篇幅有限贴几个常用的,其他的返回值大家就自己百度吧!
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
//获取以太网卡网络接口信息
IPInterfaceProperties ip = adapter.GetIPProperties();
//获取单播地址集
UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
foreach (UnicastIPAddressInformation ipadd in ipCollection)
{
//InterNetwork IPV4地址 InterNetworkV6 IPV6地址
//Max MAX 位址
if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
//判断是否为ipv4
{
strLocalIP = ipadd.Address.ToString();//获取ip
return strLocalIP;//获取ip
}
}
}
}
return null;
}