?
Solved

Get internet ip

Posted on 2004-12-01
16
Medium Priority
?
271 Views
Last Modified: 2010-04-15
string hostName = System.Net.Dns.GetHostName();

System.Diagnostics.Debug.WriteLine(System.Net.Dns.GetHostByName(hostName).AddressList[0].ToString());

=================

This gets my IP address assigned on the LAN....but how can I get my internet IP programmatically.

For example...if I go to http://www.gotomyvnc.com ....  the button will show my internet IP address.
                  
0
Comment
Question by:Tom Knowlton
  • 9
  • 5
  • 2
16 Comments
 
LVL 2

Expert Comment

by:viksi
ID: 12719329
If you are within a LAN, you will be assigned an internal IP address and that's what that function returns. To get the router IP address you will need to point to it. Your hostname in the example will return "localhost", you need the name of the router.
0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12719365
how can I point to the router?

This is for unsophisticated end-users who will not know their static IP.
0
 
LVL 2

Expert Comment

by:viksi
ID: 12719475
Is it a web application?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12719499
No.

Sorry I should have explained a little better.

This is a C# Windows application.  When it runs I want the app to detect the static IP  ......     just like what you see when you go to   http://www.ipchicken.com     for example.


0
 
LVL 2

Expert Comment

by:viksi
ID: 12719663
See, when you use a web application, such as ipchicken, to get your ip address, to their server your computer has the outside ip address (they can't see your lan address, courtesy of NAT). That's why I mentioned it.

To get your own router address, you can try and poll the router but that's not guaranteed to work. Try the following:

   IPAddress hostIPAddress = IPAddress.Parse(IpAddressString); // IpAddressString router address
   IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
   // Get the IP address list that resolves to the host names contained in
   // the Alias property.
   IPAddress[] address = hostInfo.AddressList;

   Console.WriteLine("\nIP address list : ");
   for(int index=0; index < address.Length; index++) {
      Console.WriteLine(address[index]);
   }

One of those addresses will be the outside IP of the router. To get the router address automatically, you can do the same for the current machine.

Another approach would be to use tracing. I've never done it in .NET but if you use tracert in DOS you can get to a destination while marking each point along the way.
0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12720260
I ran your code but the only IP address it listed was my internal LAN address:

private void FormTestUDP_Load(object sender, System.EventArgs e)
            {
                  string hostName = System.Net.Dns.GetHostName();
                  string yourIP = System.Net.Dns.GetHostByName(hostName).AddressList[0].ToString();
                  this.Text = this.Text + " Your machine's IP is:  " + yourIP + " (this may not be your static IP)";
                  
                  System.Net.IPAddress hostIPAddress = System.Net.IPAddress.Parse(yourIP); // IpAddressString router address
                  System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostByAddress(hostIPAddress);
                  // Get the IP address list that resolves to the host names contained in
                  // the Alias property.
                  System.Net.IPAddress[] address = hostInfo.AddressList;

                  System.Diagnostics.Debug.WriteLine("\nIP address list : ");
                  for(int index=0; index < address.Length; index++)
                  {
                        System.Diagnostics.Debug.WriteLine(address[index]);
                  }
            }


0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12720271
Like you said....it was not gauranteed to work.

Any other ideas?

btw....thanks for your help on this.
0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12720304
One thought:

I could make a call to http://www.ipchicken.com.....retrieve the HTML source.....parse it......and get my static (internet)  ip.


Dumb but might work.
0
 
LVL 8

Accepted Solution

by:
AaronReams earned 1200 total points
ID: 12720987
Hi knowlton,

Basically what Viksi alluded to is correct.  You have three options:  1) Have a server on the internet return your visible IP address to you 2) Have a router that supports returning this info to you 3) Run tracert and figure it out yourself (which is actually just an extension of option 1 ).

I was curious about this so I wrote this code to perform option 3.  This isn't the prettiest code in the world but it basically calls tracert and the parses the response.  This code assumes the router is 2 hops away.  First your card IP and then the routers IP.   Try it out and let me know what you think.  Cheers -Aaron

using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;



            [DllImport("shell32.dll", CharSet=CharSet.Auto)]
            public static extern int ShellExecute(int hwnd,string lpOperation,string lpFile,string lpParameters,string lpDirectory,int nShowCmd);



            private void button2_Click(object sender, System.EventArgs e)
            {
                  // You can use this but a popup window will appear
                  //Process.Start(@"cmd.exe",@"/c tracert.exe -d -h 2 experts-exchange.com > c:\ip.out");
                  
                  // This runs the command in the background so no popup
                  ShellExecute(this.Handle.ToInt32(),"open","cmd.exe",@"/c tracert.exe -d -h 2 experts-exchange.com > c:\ip.out",@"C:\",0);

                  // You could also use spawn then you wouldn't have to use a timeout because you could wait for the cmd to finish
                  Thread.Sleep(5000);

                  if (!File.Exists(@"c:\ip.out"))
                  {
                        MessageBox.Show("Failed to find file!");
                        return;
                  }

                  // Open the file to read from.
                  string strIP = "";
                  using (StreamReader sr = File.OpenText(@"c:\ip.out"))
                  {
                        string s = "";
                        while ((s = sr.ReadLine()) != null)
                        {
                              strIP += s;
                        }
                  }

                  int a = strIP.LastIndexOf("ms");
                  strIP = strIP.Substring(a+2);
                  strIP = strIP.Trim();

                  int b = strIP.IndexOf(" ");
                  strIP = strIP.Substring(0,b);

                  MessageBox.Show(strIP);
            }



0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12721019
What namespace is Thread under?

compiler error.
0
 
LVL 2

Assisted Solution

by:viksi
viksi earned 800 total points
ID: 12721026
As always, there are many ways to do what you want. Many of them will not be elegant, but it also depends on your goals. The reason why the code you wrote returned your own ip address was because you asked for the localhost again. You should provide a string ip address of your router. But I'm not sure if it will again get the right router.

If you are not delivering an application to an outside customer, you can write a web-service that gets the ip address. That way you don't have to do any parsing. Just access it from the outside, for example instead of using

http://localhost/getmyip.asmx

you can use

http://yourdomain.com/getmyip.asmx

I think asmx is the web-service extension.

The drawback to this solution is that you have to keep your webserver running. If that is not the problem, I think this solution will actually be the most ellegant without having to do some low level programming.

-Viksi
0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12721060
AaronReams:

You code worked on my machine.

Under what circumstances would it NOT work.....do you know?

===============

viksi:

I like AaronReams' solution....not to discount your thoughts.

I am not sure if I understood what you meant by passing the address to the router.  The whole point is I would not know this in advance.

I enourage you to take a look at AaronReams' solution.
0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12721078
NOTES:


Here is the complete source code.  Just start a new C# Windows App and replace the skeleton Form1.cs code with the following:


sing System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace WindowsApplicationGetStaticIP
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.Button button1;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            ///

            [DllImport("shell32.dll", CharSet=CharSet.Auto)]
            public static extern int ShellExecute(int hwnd,string lpOperation,string lpFile,string lpParameters,string lpDirectory,int nShowCmd);

            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.button1 = new System.Windows.Forms.Button();
                  this.SuspendLayout();
                  //
                  // button1
                  //
                  this.button1.Location = new System.Drawing.Point(136, 112);
                  this.button1.Name = "button1";
                  this.button1.TabIndex = 0;
                  this.button1.Text = "button1";
                  this.button1.Click += new System.EventHandler(this.button1_Click);
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                                              this.button1});
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                  // You can use this but a popup window will appear
                  //Process.Start(@"cmd.exe",@"/c tracert.exe -d -h 2 experts-exchange.com > c:\ip.out");
               
                  // This runs the command in the background so no popup
                  ShellExecute(this.Handle.ToInt32(),"open","cmd.exe",@"/c tracert.exe -d -h 2 experts-exchange.com > c:\ip.out",@"C:\",0);

                  // You could also use spawn then you wouldn't have to use a timeout because you could wait for the cmd to finish
                  Thread.Sleep(5000);

                  if (!File.Exists(@"c:\ip.out"))
                  {
                        MessageBox.Show("Failed to find file!");
                        return;
                  }

                  // Open the file to read from.
                  string strIP = "";
                  using (StreamReader sr = File.OpenText(@"c:\ip.out"))
                  {
                        string s = "";
                        while ((s = sr.ReadLine()) != null)
                        {
                              strIP += s;
                        }
                  }

                  int a = strIP.LastIndexOf("ms");
                  strIP = strIP.Substring(a+2);
                  strIP = strIP.Trim();

                  int b = strIP.IndexOf(" ");
                  strIP = strIP.Substring(0,b);

                  MessageBox.Show(strIP);
            }
      }
}



0
 
LVL 2

Expert Comment

by:viksi
ID: 12721140
The solution provided by AaronReams will do the job, although I would personally avoid it if the application were going to a customer. I say that because it depends on the operating system. One could end up with permission issues for one, and also, in theory, .NET is supposed to be platform independent (believe it or not, there is a Linux .NET movement).

The web-service version will work always as long as the web server is running.

As far as providing the ip address of the router, I was referring to the internal address, which is your PC's gateway.

Regardless, if you were just writing a utility, the code provided will be more than sufficient. Good job fellas :)

-Viksi
0
 
LVL 5

Author Comment

by:Tom Knowlton
ID: 12721152
Thank you both.

viksi:  Good observations on permission issues, etc....I'll keep it in mind.

Tom
0
 
LVL 8

Expert Comment

by:AaronReams
ID: 12721186
Hi there,

This should work most of the time. Some circumstances although unsual where it will not work are:

1) Your router doesn't support ICMP.  Unlikely.

2) You're more than one hop away from the router.

3) You're directly connected to the internet (no router)


Viksi is correct though.  This is definitely not the most elegant way to solve the problem.  You would really want to write some sort of discovery server that you could contact and it would send back your visible information.  

Of course, I don't know if you've considered firewalls for your project but that opens a whole other pandoras box of problems.  Although you can detect the IP it doesn't necessarily mean you can get to it.

Good luck Tom!  Thanks for the input also Viksi!

Cheers Mates!

Aaron
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Loops Section Overview
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question