尝试使用C#获取我的IP地址 [英] Trying to get my IP address Using C#

查看:103
本文介绍了尝试使用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;
}



如果您自己使用Google,它会更快
Hi ,
It will be faster if you Google it by yourself
Google[^]
Best Regards
M.Mitwalli


http://www.csharp-examples.net/local -ip/ [ ^ ]
http://www.8b1b.com/showthread.php?64-How-to-get-my-own-IP-address-in-C [如何获取机器的IP地址 [ ^ ]
http://www.csharp-examples.net/local-ip/[^]
http://www.8b1b.com/showthread.php?64-How-to-get-my-own-IP-address-in-C[^]
How To Get IP Address Of A Machine[^]


这篇关于尝试使用C#获取我的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆