Link to home
Start Free TrialLog in
Avatar of CodeYankee
CodeYankee

asked on

How To Detect My Router's Public IP Address From Inside My Own Network

Greetings All,

I have a web application that is installed at numerours remote locations (I know, not the best solution, its the way my boss wants it).  I have an install package that installs the web application for the user.  Anyway, when the web application is installed I want to detect the router's public ip address.  Anyone know of a quick and easy way to do this programmatically?  Preferably in VB.net or javacript.

Thanks,

CodeYankee
Avatar of Caiapfas
Caiapfas

yes, if its one of the linksys / home routers goto  http://192.168.1.1/ in your browser window, and type admin/admin as user/pass, then one the first page it will show the wan ip address.


if not,
What connect do you have?
what type fo router?
Static or dynamic ip?
Avatar of CodeYankee

ASKER

Yes, that will work manually.  I am looking for a solution that allows it to be done programmatically.  For example, in VB.NET I could get my own ipaddress by calling System.Net.DNS.GetHostByAddress(), but this only gets me the ipaddress for the local machine.  I want the public IP Address for my router.

Any other ideas?
You can't get the public IP address of your router because you are not in the good side because only another computer out of your lan can see the router IP Address. There is two common solutions :

1/ By Program : Use a site lik http://www.whatismyip.com/ (ther are several sites like this one) to get an html file and parse it with a regular expression parser to get the IP Address

2/ By Program : if you can get the status page of your router, then get this html file and parse it with a regular expression parser to get the IP Address


I have a prototype program in CSharp of this, if you need it as example then let me known and I'll send it to you.
Well, assuming you have a web server out there that this stuff is downloaded from.  Why not just make a webpage on a remote server that responses out the REMOTE_ADDR Server Variable?  That way you don't have to parse out a ton of crap.
Ya, that was my solution.  My boss is a friggen idiot when it comes to web development.  He wants everything to remain at the remote location.  Any other ideas???
hmmmmmmmmm.........

I don't know how you can get the router's IP internally without having to code specifically for different routers.  I think you could pass a username and password to a linksys or similar router and get to the page that shows the external IP address, but damn what a pain in the ass...

Example on a linksys:  http://[router username]:[router password]@192.168.1.1/whatever-the-file-is-that-shows-the-ip.html

You'll still have to parse the output like Christian said using RegExp
ASKER CERTIFIED SOLUTION
Avatar of vikram_1982
vikram_1982

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
One problem I can see with this is in the instance where the router is behind another router behind another router, etc.

Big companies have this kind of situation sometimes.
A Router behind a router, behind another in the same network???  This is the first time i am hearing of such a thing..

Why will such a setup be necessary? I am not sure. I have knowledge of switches and bridges and hubs being used behind routers to increase the capacity, but a router behind another router is something i need to look into.

Still, i would reckon that if this is the case, you would never know. How can u determine how many routers there are between the external router of the network and the router to which a particular system is connected to.

Maybe.. u can incrementally perform this ping operation until a time you dont get a 192.168.0.0/24 address.

I guess you can understand what i am trying to say....

Vikram.
Don't question it...  Just go with it.  The point is people do stupid things and he has to work with it.  Haha
>>> I have a web application that is installed at numerours remote locations <<<

I believe that you are storing the web application in the web server. I can almost guarantee you that the web server will be behind a single router of the network. If it behind a router, behind another, then the web server would get a local LAN IP Address and it will not be accessible by the outside world. So, i would say it is a safe bet to go ahead with the ping program.

Vikram
Anyways.. Let us not be banging our heads about something hypothetical as of now.. Let us see if the author of this thread really has this requierement or not..

:)

Vikkki
Vikram,

I like your solution.  I am going to test it out.  Unless anybody comes up with something better, you get the points.  Give me a day to test this out first.
Sure man...

Vikkki
Ya, the statement "I have a web application that is installed at numerours remote locations" is pretty sad, isn't it?  I have talked to my boss until I am blue in the face trying to convince him to go to one central server.  I am dealing with monkeys here.  Its friggen "Office Space" the movie in reality at this place.  They may as well rename the company Initech.
Haha.. Pretty bad scenario eh CodeYankee..

Dont worry, u are in Good Company..Many of us share the same problems..
:)

Vikram
Thanks

Vikram.
Blablabla. The solutions I done are goods and Ashley Bryant is in the good way : accept the solution from Christian (where are my points???).

Ok, Ok, I'm here to exchanges with the community and to be humble, maybe it exists better solution but my solutions work fine. Think that your provider can add a router or block ping calls.

Virkram and other, I can send to you the full source in C# of my program on demand. I wrote it when I needed to publish the IP address of my home computer to friends.
The program allows you to connect directly on your router if possible (ex : linksys...) else (ex: SMC) to web sites that publish your IP address. To connect to your router you can enter URL, UserId and Password from the tab "IP from router", else select the tab "IP from Web" and check one or more URL to get your IP Address. You can configure the address to use from the status page of the router. And you can specify URL, UserId and Password to send a HTML page to a static web site (in my case provided by ma ISP) the publish your IP Address. It supposed to work even if you don't have a router.

Let me know if you want the source : send me your e-mail.

Friendly.
Christian

PS : Maybe it's not bug free but it works. You only need Visual Studio C#.
Go to your browser type www.myipaddress.com this will give your IP address for the router.
If you are trying to access your application from outside u have to configure the router.
Just as an aside, if you have the situation as described (router behind router behind...) then the only way to get the true internet-facing IP address is something like the myipaddress.com site.  
It's the only way to guarantee that what you are pointing at is the external IP, as you might have router upon router ad infinitum, you can't tell when you get to a real address without checking the returned IP and recursing every time you find a non-routable address (192.168.x.x or 10.x.x.x, etc.)

As vikram_1982 said though, if it's more than one level deep, you probably won't be able to see it.
I am a little confused? What router address are you looking for? In a two router situation (see below) there is the WAN and the LAN side of a given router?

Example:

Client IP = 192.168.10.100
Client GW = 192.168.10.1

ROUTER A
Client Router IP LAN = 192.168.10.1
Client Router IP WAN = 192.168.100.100

ROUTER B
Property / Internet Router LAN = 192.168.100.1
Property / Internet Router WAN = 24.234.0.xxx

If the application is a web based application and is running on a Windows machine with IIS or PWS you can use the following code to view the IP of any routers WAN address.  In the case of the example the IIS or PWS server would need to exist in the 192.168.100.xxx network.  By entering the workstation or servers FQDN/clientinfo.asp you would be able to pull the ROUTER A's WAN IP address and populate a cookie or server side varible.  If you load the following code on your public web server you would be able to view ROUTER B's WAN address.

::::Example Code::::

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<html>
<head>
<title>Remote Client Info</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.label {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 12pt;
      font-style: normal;
      font-weight: bold;
      font-variant: normal;
      text-transform: capitalize;
      color: #000099;
      text-align: right;
      border: none #666666;
}
.data {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 12pt;
      font-style: normal;
      font-weight: bold;
      font-variant: normal;
      color: #FF0000;
      text-align: left;
      border: none #666666;
}
.title {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 12pt;
      font-weight: bolder;
      text-transform: uppercase;
      color: #666666;
      text-decoration: underline;
      text-align: center;
      background-position: center;
}

.tbl {
      background-color: #FFFFD9;
      border: inset #999999;
      text-align: center;
      background-position: center;
      align: center;
}
body {
      text-align: center;
}
-->
</style>
</head>

<body>

  <%
      ua = Request.ServerVariables("HTTP_USER_AGENT")
      os = Request.ServerVariables("HTTP_UA_OS")
      If Instr(ua, "MSIE") Then
            If Instr(ua, "MSIE 6.") Then
                  Browser = "Microsoft Internet Explorer 6.x"
            Elseif Instr(ua, "MSIE 5.") Then
                  Browser = "Microsoft Internet Explorer 5.x"
            Elseif Instr(ua, "MSIE 4.") Then
                  Browser = "Microsoft Internet Explorer 4.x"
            Elseif Instr(ua, "MSIE 3.") Then
                  Browser = "Microsoft Internet Explorer 3.x"
                  If Instr(ua, "MSIE 3.02") Then
                        Browser = "Microsoft Internet Explorer 3.02"
                  End If
            Else
                  Browser = "Microsoft Internet Explorer"
            End If
      ElseIf Instr(ua, "Mozilla") and Instr(ua, "compatible") = 0 Then
            If Instr(ua, "Mozilla/4") Then
                  Browser = "Netscape Navigator 4.x"
            Elseif Instr(ua, "Mozilla/3") Then
                  Browser = "Netscape Navigator 3.x"
            Else
                  Browser = "Netscape Navigator"
            End If
      End If
      
      If Instr(ua, "Windows 95") or Instr(ua, "Win95") Then
            System = "Windows 95"
      Elseif Instr(ua, "Windows 98") or Instr(ua, "Win98") Then
            System = "Windows 98"
      Elseif Instr(ua, "Windows 3.1") or Instr(os, "Win16") Then
            System = "Windows 3.x/Windows NT 3.x"
      Elseif Instr(ua, "5.1") or Instr(oa, "Windows NT 5.1") Then
            System = "Windows XP"
      Elseif Instr(ua, "NT") or Instr(oa, "NT") Then
            System = "Windows NT"
      Elseif Instr(ua, "Mac") Then
            System = "Mac"
            If Instr(ua, "PowerPC") or Instr(ua, "PPC") Then
                  System = "Mac PPC"
            Elseif Instr(ua, "68000") or Instr(ua, "68K") Then
                  System = "Mac 68K"
            End If
      Elseif Instr(ua, "X11") Then
            System = "UNIX"
      End If
%>
<div class="title">Remote Client Information</div><br>
<table class="tbl" width="50%" border="0" cellpadding="0" cellspacing="0">
  <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
  </tr>
  <tr>
    <td class="label">Current Browser:&nbsp;</td>
    <td class="data"><%=Browser%>&nbsp;</td>
  </tr>
  <tr>
    <td class="label">Current Operating System:&nbsp;</td>
    <td class="data"><%=System%>&nbsp;</td>
  </tr>
  <tr>
    <td class="label">Current IP:&nbsp;</td>
    <td class="data"><%=Request.ServerVariables("Remote_Addr")%>&nbsp;</td>
  </tr>
  <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
  </tr>  
</table>

</body>
</html>


Not sure if it helps.  Solution B would be to get an account at DYNDNS.ORG and use a freeware client which would load to your clients PC.  The freeware dyndns client would constantly update the dyndns server with the most current router information at which point you could use your DNS server and create CNAME alaises for each of the dyndns.org client addresses.

Let me know any more speifics.

-V.V.
The easiest way possible is to visit the website www.whatismyip.com
I built a program for checking my ip to find out if it's changed. Here are some snippits you might like  (I'm going to turn it into an ASP.net component soon enough)
I have a list of websites that give out your IP address.   Any External hosting you have that can run simple ASP or Javascript commands could run your own page too. Just have it print out "Request.UserHostAddress.ToString"  (ASP.net)




[Code]
  'Takes in website HTML, looks for a valid IP address (if a website is put in the list that displays
    'some other IP address first, it WILL NOT know the difference)
Private Function get_ip() As String

        Dim url As String
        Try
'This is the responce from another function

            url = get_list()
        Catch ex As Exception
            MsgBox("There was a problem getting IP address, check URL list file, or your connection")
        End Try
        'Regular expression to check for valid IP
        Dim r As New Regex("\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")

   
        Dim m As Match = r.Match(url)
        Dim ma As Match
        'Extracts just the matching string
        ma = r.Match(url)
        Return ma.Value.ToString
    End Function

[/Code]
'This just downloads the contents of a webpage. I have an array of the websites that I load in from an XML file, you can make your own list
'The previous code will work on the ones already posted above.
 Dim ip_add As String
Dim list As New WebClient
Dim temp As Byte()
 temp = list.DownloadData(urls.Item(CInt(Int((urls.Count * Rnd()) + 0))))

                ip_add = System.Text.Encoding.ASCII.GetString(temp)

return ip_add
[Code]
Hi,

thought I would add the solutions I found, since the accepted answer did not work for me, when I ran into the same problem of having to detect a router's WAN-IP. The ping -r 1 www.yahoo.com always results in timeouts for me.

And the problem with sites like whatsmyip.com is that they will return the proxy-server's address if one is being used and not the WAN-IP of the router. So far there is only one site that I found that really returns the correct WAN-IP, even if a proxy is used on Port 80:

http://checkip.dyndns.org

Another solution I found is to use a little freeware tool called cmdNET by JPSoft in Denmark. It is a command line tool for Windows/DOS which will write both, the internal network IP of the computer being used as well as the WAN-IP of the router to a text file, which you can then read with your application. Since cmdNET requested access to the net though, it might well be that the WAN-IP was returned from some webserver too in this case, not sure.

I have checked both solutions with a Netgear as well as a USRobotics router.

I have yet to find out what dyndns.org really does to detect the WAN-IP since I don't really want to rely on 3rd party websites, but would like to add such a routine to my own webserver and check via there instead of via http://checkip.dyndns.org .

hth,
Max
duh! forgot to give the link to the freeware tool cmdNET:

download page:
http://www.jpsoft.dk/download.html

direct download link:
http://www.jpsoft.dk/exe/cmdnet.zip

Max
If your router supports snmp you could use an snmpget command to retieve the address
This is not an odd setup, many people have web servers behind several routers, and it's no big deal to forward the packets from the outside... hence the name... routing...  I don't know how to do it in VB though, C# is the only way to go...  Instead of determining your end users location based on the IP of the computer they request it from, why not use geolocation to identify their geological region based on the CLIENT IP address...  Just gather the client IP ( ServerVariables("REMOTE_ADDR")) and compare it against a geoip database (there are several available free), with something like SELECT location FROM GeoIP where IP Address BETWEEN begin_ip AND end_ip.  That's how I would approach it...  
of course, you have to keep in mind that you will have to parse and calculate the IP address with IP = 16777216*w + 65536*x + 256*y + z where your IP address is w.x.y.z... of course, you'd have to be more creative if you wanted it to continue to function with IPV6... but again... a few extra lines of code...
The logical way to do this by using the ping command (as Vikram said) and capturing the results. The problem is that you don't want to be reliant on another website. You can get around this by pinging the WAN DNS server (your ISP's DNS server), if this is down, your router won't be working anyway.

Do the following:

ping -r 9 dns.server.com (or whatever it is called)
capture the results
select all the (up to 9) IP addresses in to an array
scan the array for the first IP Address that doesn't begin with the following (they are all reserved for local networks):
    10.
    172.16.
    192.168.
    169.254.
This will almost definitely be the router's IP address unless you route through 8 or 9 devices!
You can't do it that way unless you have a 2nd computer. And if you know a DNS of a computer, there is no point in trying to find out the IP, because you can just do a quick lookup of the DNS. The point would be a computer trying to find it's own IP.


My current (external) IP is 161.184.12.13X here is a list of the IP's from the ping -r 9 to my ISP  (can't do it to myself because we don't know our own IP)

 161.184.245.22: byt
 154.11.95.173 ->
 154.11.98.75 ->
 161.184.255.145 ->
 161.184.245.4 ->
 161.184.245.22 ->
 161.184.255.150 ->
 154.11.98.73 ->
 154.11.95.174 ->
 142.173.144.1


Notice how my ip is not on that list?

Notice how my routers internal IP is also not on that list? Even with a tracert 192.168.1.1 doesn't apper.

The code I submitted earlier would work if you can get it to accept the password, and then skip the first 2 IP's found on my linksys router.

However, if this is for a client's application, I would assume you wouldn't have the router password.
Try This it is vbscript...

It stores it to a variable called strText reading "Current Ip Address: WWW.XXX.YYY.ZZZ"



Dim objIE

set objIE=createobject("InternetExplorer.Application")
    objIE.height = 300
    objIE.width = 200
    objIE.left = 300
    objIE.top = 200
    objIE.menubar = false
    objIE.toolbar = false
    objIE.statusbar = false
    objIE.resizable = false
    objIE.fullscreen = false
    objIE.navigate "http://checkip.dyndns.org/" or "http://checkip.dyndns.org:8245/"
    objIE.visible=false

DO WHILE objIE.Busy

   Wscript.sleep 1000

Loop

strText = objIE.Document.body.innerhtml

msgbox strText

objIE.Quit

The URL with the 8245 port gets around some proxy servers, which causes the IP address to read out backwards.

Kstr79

I would suggest taking a look at a program called Samourize, it is a desktop mod software and on it your can do all kinds of things using VB for your IP's, HDD, everythign really.
For future people who read the site an alternative is to make a simple program thats finds the textbox on http://www.ipbot.net/index2.htm and gather the external ip from there
I have an ActiveX Dll that is painless.  It's this simple:

Private Sub Form_Load()

    Dim MyIpAddr As ExternalIPAddrDLL.CMyExternalIPAddr
   
    Set MyIpAddr = New ExternalIPAddrDLL.CMyExternalIPAddr
   
    MsgBox MyIpAddr.ExternalIPAddress
   
    Set MyIpAddr = Nothing

End Sub

I also have an ActiveX Control that does the same thing, basically.

sfrase@frasesoftware.com
Imports System.Text.RegularExpressions

#Region " Declaraciones : External IP "

    Public Function IsValidIPAddress(ByVal Data As String) As Boolean
        Dim zl As Integer
        zl = Data.Length()
        If zl < 15 Then
            Return Regex.IsMatch(Data, "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")
        Else
            IsValidIPAddress = False
        End If
    End Function
    Public Function zgetextip2() As String
        Dim reader As XmlTextReader
        reader = New XmlTextReader("http://www.showmyip.com/xml/")

        While reader.Read()
            Select Case (reader.NodeType)
                Case XmlNodeType.Element
                    If (reader.Name = "ip") Then
                        zgetextip2 = reader.ReadElementString()
                        Exit While
                    End If
            End Select
        End While

    End Function
    Public Function zgetextip() As String
        Dim wclient As New System.Net.WebClient
        Dim stream1 As Stream

        stream1 = wclient.OpenRead("http://www.whatismyip.com/")
        If stream1.CanRead Then
            Dim buffer1 As Byte() = New Byte(256 - 1) {}
            stream1.Read(buffer1, 0, 256)
            Dim text1 As String = Encoding.ASCII.GetString(buffer1, 0, 256)
            text1 = text1.Substring((text1.IndexOf("IP Is ") + 6), 15)
            If (text1.IndexOf(" ") > -1) Then
                Dim chArray1 As Char() = New Char() {" "c}
                text1 = text1.Split(chArray1)(0)
            End If
            zgetextip = text1
            If IsValidIPAddress(zgetextip) = False Then
                zgetextip = zgetextip2()
            End If
        Else
            zgetextip = zgetextip2()
        End If

    End Function
#End Region
Try this way:

namespace GetExternalIP
{
      // Usage:
      // Just compile and run GetExternalIP.exe at the command prompt to see your public
      // facing IP.  If your behind a firewall or DSL/router, this will be the public IP
      // of that device.  You could redirect output to a file and mail to yourself using
      // sendmail (or other) and a scheduled job.
      class Class1
      {
            [STAThread]
            static void Main(string[] args)
            {
                  try
                  {
                        // Use a web page that displays the IP of the request.  In this case,
                        // I use network-tools.com.  This page has been around for years
                        // and is always up when I have tried it.  You could use others or
                        // your own.  
                        WebRequest myRequest = WebRequest.Create("http://network-tools.com");

                        // Send request, get response, and parse out the IP address on the page.
                        using(WebResponse res = myRequest.GetResponse())
                        {
                              using(Stream s = res.GetResponseStream())
                              using(StreamReader sr = new StreamReader(s, Encoding.UTF8))
                              {
                                    string html = sr.ReadToEnd();
                                    Regex regex = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
                                    string ipString = regex.Match(html).Value;
                                    Console.WriteLine("Public IP: "+ipString);
                              }
                        }
                  }
                  catch(Exception ex)
                  {
                        Console.WriteLine("Error getting IP Address:\n"+ex.Message);
                  }
            }
      }
}


Greetings

fferdinan
I would like to add to this by asking a question...

I am currently using a program called BGinfo.exe from sysinternals.com
the program writes to the background of your desktop with ipadress from your LAN.  

my company uses this program on all remote users machines.

the only thing this program does not do is display the  external ipaddress. it has a custom field but i am not able to configure it do display the external ipaddress.  it has options for an "environment variable" or a reg value or a "vbscript" or a wmi query. and or even maybe write a .bat file to write to a txt file where this progam can read from.

can some one come up with the best way to display this external ip for program.  

I dont know how to code, but if you can explain i can learn fast.

thanks all

Mperez738
two simple commands:

wget http://dynupdate.no-ip.com/ip.php
cat ip.php


dave
http://www.itsyourip.com

Just if someone is looking.