c#获取本机ip地址|获取本机的本地上网IP地址
具体方法为如下:
private void btnChenk_Click(object sender, System.EventArgs e)
{
System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if ( addressList.Length>1)
{
nativeIP.Text = addressList[0].ToString();
serverIP.Text = addressList[1].ToString();
}
else
{
nativeIP.Text = addressList[0].ToString();
serverIP.Text = "Break the line...";
}
}
通常addressList[]所得到的列表就是当前的IP地址;
如果当前是拨号上网的话addressList[0].ToString()就是
本地IP地址;addressList[1].ToString() 就是上网地址。
如果当前是使用[EnterNet 300]拨号上网的话addressList[1].ToString()
就是本地IP地址;addressList[0].ToString() 就是上网地址。
如果程序只能够检测到只有一个IP地址的话,证明当前
电脑没有在线!
获取客户端IP:
1private void ButtonIP_Click(object sender, System.EventArgs e)
2{
3 Syste m.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
4if ( addressList.Length>1)
5{
6TextLIP.Text = addressList[0].ToString();
7TextSIP.Text = addressList[1].ToString();
8}
9else
10{
11TextLIP.Text = addressList[0].ToString();TextSIP.Text = "没有可用的连接";
12}
13}
14
15
using System.Management;
string stringMAC = "";
string stringIP = "";
ManagementClass MC = new ManagementClass "Win32_NetworkAdapterConfiguration");
ManagementObjectCollection MOC= MC.GetInstances();
foreach(ManagementObject MO in MOC)
{
if ((bool)MO["IPEnabled"] == true){stringMAC += MO["MACAddress"].ToString();
TextMAC.Text = stringMAC.ToString();
string[] IPAddresses = (string[]) MO["IPAddress"];
if(IPAddresses.Length > 0)
stringIP = IPAddresses[0];TextIP.Text = stringIP.ToString();
}
}
Code
获取客户端MAC地址:
Code
获取服务器IP一:
1private void ButtonIP_Click(object sender, System.EventArgs e)
2{
3 Syste m.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
4if ( addressList.Length>1)
5{
6TextLIP.Text = addressList[0].ToString();
7TextSIP.Text = addressList[1].ToString();
8}
9else
10{
11TextLIP.Text = addressList[0].ToString();TextSIP.Text = "没有可用的连接";
12}
13}
14
15
获取服务器IP及MAC地址二:
using System.Management;
string stringMAC = "";
string stringIP = "";
ManagementClass MC = new ManagementClass "Win32_NetworkAdapterConfiguration");
ManagementObjectCollection MOC= MC.GetInstances();
foreach(ManagementObject MO in MOC)
{
if ((bool)MO["IPEnabled"] == true){stringMAC += MO["MACAddress"].ToString();
TextMAC.Text = stringMAC.ToString();
string[] IPAddresses = (string[]) MO["IPAddress"];
if(IPAddresses.Length > 0)
stringIP = IPAddresses[0];TextIP.Text = stringIP.ToString();
}
}
命运负责洗牌,但是玩牌的是我们自己!