本文介绍了尝试使用C#获取我的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用C#在窗口标签上打印我的IP地址-它只有几行代码,但几乎像MAC地址一样打印垃圾信息.我听说可能需要一个循环,但是我假设它将是AddressList中的第一个IP地址.代码如下:
Hi, I''m trying to print my IP Address on a window label using C# - it''s only a couple of lines of code but prints garbage, almost like a MAC address. I''ve heard a loop might be needed but I''m assuming it will be the first IP address in AddressList. Here''s the code:
private void Form1_Load(object sender, EventArgs e)
{
IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
//IPHostEntry IPHost = Dns.GetHostByName();
lblStatus.Text = "My IP address is " + IPHost.AddressList[0].ToString();
alSockets = new ArrayList();
Thread thdListener = new Thread(new ThreadStart(listenerThread));
thdListener.Start();
}
非常感谢任何帮助.
Any help much appreciated.
推荐答案
public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
这篇关于尝试使用C#获取我的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!