Get internet ip

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.
                  
LVL 5
Tom KnowltonWeb developerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

viksiCommented:
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
Tom KnowltonWeb developerAuthor Commented:
how can I point to the router?

This is for unsophisticated end-users who will not know their static IP.
0
viksiCommented:
Is it a web application?
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Tom KnowltonWeb developerAuthor Commented:
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
viksiCommented:
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
Tom KnowltonWeb developerAuthor Commented:
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
Tom KnowltonWeb developerAuthor Commented:
Like you said....it was not gauranteed to work.

Any other ideas?

btw....thanks for your help on this.
0
Tom KnowltonWeb developerAuthor Commented:
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
AaronReamsCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Tom KnowltonWeb developerAuthor Commented:
What namespace is Thread under?

compiler error.
0
viksiCommented:
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
Tom KnowltonWeb developerAuthor Commented:
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
Tom KnowltonWeb developerAuthor Commented:
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
viksiCommented:
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
Tom KnowltonWeb developerAuthor Commented:
Thank you both.

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

Tom
0
AaronReamsCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.