I cant seem to get or find information on finding my routers public IP? Is this because it cant be done this way and would have to get it from a website?
You may use Telnet to programmatically query your router for the WAN IP.
The Telnet part
The Telnet part can be accomplished using, for example, this Minimalistic Telnet code as an API to send a Telnet command to your router and get the router's response. The remainder of this answer assumes you are set up in one way or another to send a Telnet command and get back the response in your code.
Limitations of approach
I will say up front that one drawback of querying the router compared to other approaches is that the code you write is likely to be fairly specific to your router model. That said, it can be a useful approach that doesn't rely on external servers, and you may anyway wish to access your router from your own software for other purposes, such as configuring and controlling it, making it more worthwhile writing specific code.
Example router command and response
The example below will not be right for all routers, but illustrates the approach in principle. You will need to change the particulars to suit your router commands and responses.
For example, the way to get your router to show the WAN IP may be the following Telnet command:
connection list
The output may consist of a list of lines of text, one per connection, with the IP address at offset 39. The line for the WAN connection may be identifiable from the word "Internet" somewhere in the line:
RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
<------------------ 39 -------------><-- WAN IP -->
The output may pad each IP address segment out to three characters with spaces, which you will need to remove. (That is, in the xample above, you would need to turn "146.200.253. 16" into "146.200.253.16".)
By experimentation or consulting reference documentation for your router, you can establish the command to use for your specific router and how to interpret the router's response.
Code to get the WAN IP
(Assumes you have a method sendRouterCommand
for the Telnet part—see above.)
Using the example router described above, the following code gets the WAN IP:
private bool getWanIp(ref string wanIP)
{
string routerResponse = sendRouterCommand("connection list");
return (getWanIpFromRouterResponse(routerResponse, out wanIP));
}
private bool getWanIpFromRouterResponse(string routerResponse, out string ipResult)
{
ipResult = null;
string[] responseLines = routerResponse.Split(new char[] { '\n' });
// RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
//<------------------ 39 -------------><--- 15 --->
const int offset = 39, length = 15;
foreach (string line in responseLines)
{
if (line.Length > (offset + length) && line.Contains("Internet"))
{
ipResult = line.Substring(39, 15).Replace(" ", "");
return true;
}
}
return false;
}