你试试这个,获取正确可用的IP地址:
private IPAddress getIdAddress(){
//IPHostEntry ipEntity = DnsGetHostEntry(DnsGetHostName());
////IPAddress ipAddr = ipEntityAddressList[0];
//IPAddress ipAddr = DnsGetHostAddresses(DnsGetHostName())[0];
//if (ipAddrAddressFamily == SystemNetSocketsAddressFamilyInterNetworkV6)//判断是否IP6协议
//{ // ipAddr = DnsGetHostEntry(DnsGetHostName())AddressList[1]; //}
IPAddress ipAddr = null;
IPAddress[] arrIP = DnsGetHostAddresses(DnsGetHostName());
foreach (IPAddress ip in arrIP)
{
if (SystemNetSocketsAddressFamilyInterNetworkEquals(ipAddressFamily))
{
ipAddr = ip;
break;
}
else if (SystemNetSocketsAddressFamilyInterNetworkV6Equals(ipAddressFamily))
{
ipAddr = ip;
}
} return ipAddr;
}
之前的即时通讯里面用的
我自己写的 你可以参考一下 using systemnetNetworkInformation
private void button1_Click(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterfaceGetAllNetworkInterfaces();
thislistBox1ItemsClear();
//远程服务器ip
string remoteHostNameAddress = thistextBox1TextTrim();
//构造Ping实例
Ping pingSender = new Ping();
//Ping选项设置
PingOptions options = new PingOptions();
optionsDontFragment = true;
//测试数据
string data = "test data abcabc";
byte[] buffer = EncodingASCIIGetBytes(data);
//设置超时时间
int timeout = 120;
//调用同步send方法发送数据,将返回结果保存至PingReply实例
PingReply reply = pingSenderSend(remoteHostNameAddress, timeout, buffer, options);
if (replyStatus == IPStatusSuccess)
{
foreach (NetworkInterface adapter in adapters)
{
listBox1ItemsAdd("答复的主机地址:" + replyAddressToString());
listBox1ItemsAdd("往返时间:" + replyRoundtripTime);
listBox1ItemsAdd("生存时间(TTL):" + replyOptionsTtl);
listBox1ItemsAdd("MAC地址:" + adapterGetPhysicalAddress());
}
}
else
{
listBox1ItemsAdd(replyStatusToString());
}
}
在按钮的click事件中写以下代码Process p = ProcessStart("C:\\11exe"); //启动一个进程,并运行一个exe文件 //获取IP地址string IPAdressString = "0000";
IPAddress ipAddress =DnsGetHostEntry(getHostName())AddressList[0];
IPAdressString = ipAddressToString(); //获取MACSystemManagementManagementClass mc = new SystemManagementManagementClass("Win32_NetworkAdapterConfiguration");
SystemManagementManagementObjectCollection moc = mcGetInstances();
SystemTextStringBuilder sb = new SystemTextStringBuilder();
foreach(SystemManagementManagementObject mo in moc)
{
if((bool)mo["IPEnabled"] == true) {
sbAppend(mo["MacAddress"]ToString()); }
moDispose();
}
string mac = sbToString();
是测试连通性么?
是的话类似于这样的代码:
首先需要添加:
using SystemNetNetworkInformation;
using SystemNet;
然后button的Click里添加:
IPAddress ip = IPAddressParse(textBox1Text);
Ping p = new Ping();
PingReply pr=pSend(ip, 10); //超时=10秒
if (prStatus == IPStatusSuccess)
textBox2Text="Success";
else textBox2Text="Failed";
当然更详细的状态可以再prStatus里获得
以上就是关于vs2008C#获取IP地址的问题全部的内容,包括:vs2008C#获取IP地址的问题、C# winform点击按钮获取指定ip的mac地址代码怎么写、想做个WinForm程序,在点击一下按钮就实现打开另外一个已有的应用程序,以及检测主机的IP和MAC等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)