Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# Networking
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 1-Sep-12 0:17am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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;
}
  Permalink  
Comments
Prasad_Kulkarni at 3-Sep-12 2:47am
   
My 5!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Hi ,
It will be faster if you Google it by yourself
Google[^]
Best Regards
M.Mitwalli
  Permalink  
Comments
Prasad_Kulkarni at 3-Sep-12 2:47am
   
Yes, A 5!
Mohamed Mitwalli at 3-Sep-12 2:56am
   
Thanks Prasad
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

  Permalink  
Comments
Prasad_Kulkarni at 3-Sep-12 2:47am
   
5'ed :D
ridoy at 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)

  Print Answers RSS
0 Peter Leow 160
1 Mika Wendelius 156
2 Abhinav S 155
3 Sergey Alexandrovich Kryukov 115
4 TheRealSteveJudge 114
0 Sergey Alexandrovich Kryukov 8,593
1 OriginalGriff 6,536
2 Peter Leow 3,727
3 Zoltán Zörgő 3,436
4 Richard MacCutchan 2,417


Advertise | Privacy | Mobile
Web03 | 2.8.150123.1 | Last Updated 1 Sep 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100