Click here to Skip to main content
15,512,456 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

C#
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;
}
 
Share this answer
 
Comments
Prasad_Kulkarni 3-Sep-12 2:47am    
My 5!
Hi ,
It will be faster if you Google it by yourself
Google[^]
Best Regards
M.Mitwalli
 
Share this answer
 
Comments
Prasad_Kulkarni 3-Sep-12 2:47am    
Yes, A 5!
Mohamed Mitwalli 3-Sep-12 2:56am    
Thanks Prasad
 
Share this answer
 
Comments
Prasad_Kulkarni 3-Sep-12 2:47am    
5'ed :D
ridoy 3-Sep-12 4:31am    
thanks Prasad

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900