How to Get *Internet* Ip

How to get *internet* IP?

Try this:

static IPAddress getInternetIPAddress()
{
try
{
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress gateway = IPAddress.Parse(getInternetGateway());
return findMatch(addresses, gateway);
}
catch (FormatException e) { return null; }
}

static string getInternetGateway()
{
using (Process tracert = new Process())
{
ProcessStartInfo startInfo = tracert.StartInfo;
startInfo.FileName = "tracert.exe";
startInfo.Arguments = "-h 1 208.77.188.166"; // www.example.com
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
tracert.Start();

using (StreamReader reader = tracert.StandardOutput)
{
string line = "";
for (int i = 0; i < 9; ++i)
line = reader.ReadLine();
line = line.Trim();
return line.Substring(line.LastIndexOf(' ') + 1);
}
}
}

static IPAddress findMatch(IPAddress[] addresses, IPAddress gateway)
{
byte[] gatewayBytes = gateway.GetAddressBytes();
foreach (IPAddress ip in addresses)
{
byte[] ipBytes = ip.GetAddressBytes();
if (ipBytes[0] == gatewayBytes[0]
&& ipBytes[1] == gatewayBytes[1]
&& ipBytes[2] == gatewayBytes[2])
{
return ip;
}
}
return null;
}

Note that this implementation of findMatch() relies on class C matching. If you want to support class B matching, just omit the check for ipBytes[2] == gatewayBytes[2].

Edit History:

  • Updated to use www.example.com.
  • Updated to include getInternetIPAddress(), to show how to use the other methods.
  • Updated to catch FormatException if getInternetGateway() failed to parse the gateway IP. (This can happen if the gateway router is configured such that it doesn't respond to traceroute requests.)
  • Cited Brian Rasmussen's comment.
  • Updated to use the IP for www.example.com, so that it works even when the DNS server is down.

Getting the internet ip without calling an external server

You will probably not be able to grab your public IP Address without making a request to an external server, as your device is inside a LAN, it doesn't care about the public IP address of the router to Internet because it doesn't need it !

I would suggest you to use web-services like http://checkip.amazonaws.com/ to meet your needs.

    URL getIP = new URL("http://checkip.amazonaws.com/");
BufferedReader getIPReader = new BufferedReader(new InputStreamReader(getIP.openStream()));

System.out.println(getIPReader.readLine()); // prints the IP

Getting a machine's external IP address with Python

If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.

Getting the 'external' IP address in Java

I am not sure if you can grab that IP from code that runs on the local machine.

You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:

request.getRemoteAddr()

Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.

Use a webservice like AWS and others

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

Linux / C++: Get Internet IP Address (not local computer's IP)

  1. You can write socket code to send an http request to that link.

  2. Under unix/linux/cygwin you can use system("wget http://www.whatismyip.com/automation/n09230945.asp"); then open the file "n09230945.asp" and read its contents.

Here is an example of how to make the request using sockets (I modified an online example for this specific purpose). NOTE: It is an example and a real implementation would need to handle the errors better:

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define RCVBUFSIZE 1024

int main(int argc, char *argv[])
{
int sock; // Socket descriptor
struct sockaddr_in servAddr; // server address
unsigned short servPort; // server port
char const *servIP; // Server IP address (dotted quad)
char const *request; // String to send to server
char recvBuffer[RCVBUFSIZE]; // Buffer for response string
unsigned int requestLen; // Length of string to send
int bytesRcvd; // Bytes read in single recv()
bool status = true;

// Initialize port
servIP = "72.233.89.199";
servPort = 80;
request = "GET /automation/n09230945.asp HTTP/1.1\r\nHost: www.whatismyip.com\r\n\r\n";

std::cout << request << std::endl;

/* Create a reliable, stream socket using TCP */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
status = false;
}

if (status)
{
// Convert dotted decimal into binary server address.
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(servIP);
servAddr.sin_port = htons(servPort);

// Connect to the server.
if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
{
status = false;
}
}

if (status)
{
// Calculate request length.
requestLen = strlen(request);

// Send the request to the server.
if (send(sock, request, requestLen, 0) != requestLen)
{
status = false;
}
}

if (status)
{
std::cout << "My IP Address: ";

if ((bytesRcvd = recv(sock, recvBuffer, RCVBUFSIZE - 1, 0)) <= 0)
{
status = false;
}

if (status && (bytesRcvd >0) && (bytesRcvd < (RCVBUFSIZE-1)))
{
recvBuffer[bytesRcvd] = '\0';
std::cout << recvBuffer << std::endl;
}
}

close(sock);

return 0;
}

How to get the public IP address of the device

I have used ALSystemUtilities in the past. You basically have to make a call externally to find this out.

+ (NSString *)externalIPAddress {
// Check if we have an internet connection then try to get the External IP Address
if (![self connectedViaWiFi] && ![self connectedVia3G]) {
// Not connected to anything, return nil
return nil;
}

// Get the external IP Address based on dynsns.org
NSError *error = nil;
NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
encoding:NSUTF8StringEncoding
error:&error];
if (!error) {
NSUInteger an_Integer;
NSArray *ipItemsArray;
NSString *externalIP;
NSScanner *theScanner;
NSString *text = nil;

theScanner = [NSScanner scannerWithString:theIpHtml];

while ([theScanner isAtEnd] == NO) {

// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;

// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;

// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
[ NSString stringWithFormat:@"%@>", text]
withString:@" "] ;
ipItemsArray = [theIpHtml componentsSeparatedByString:@" "];
an_Integer = [ipItemsArray indexOfObject:@"Address:"];
externalIP =[ipItemsArray objectAtIndex:++an_Integer];
}
// Check that you get something back
if (externalIP == nil || externalIP.length <= 0) {
// Error, no address found
return nil;
}
// Return External IP
return externalIP;
} else {
// Error, no address found
return nil;
}
}

Source from ALSystemUtilities



Related Topics



Leave a reply



Submit