0

the way how we get Ip address using java code is clear and many questions about this subject were answered.

but assuming that you have Vmware or VirtualBox on your machine,so you will have extra virtual network cards each one have its own Ip Address.

when executing a little program the result was like 192.168.x.x which belongs to one of my virtual network adapters. but using "What Is My IP" the result was like 197.x.x.x

so how can i get the ip adress of the connected interface ?

hannibal
  • 266
  • 4
  • 15

2 Answers2

0

Your interface IP 192.168.x.x is your local adapter interface. The prefix 192.168 indicates that this is a private non-routable address that is valid only behind a NAT firewall.

The IP returned by WhatIsMyIP is the external address of the firewall/gateway through which you access the Internet. Unless your computer is connected directly to the Internet these two addresses will never be the same.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

this should do the trick:

import java.io.*;
import java.util.*;

public class ExecTest {
public static void main(String[] args) throws IOException {
    Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");

    BufferedReader output = new BufferedReader(new            InputStreamReader(result.getInputStream()));
    String thisLine = output.readLine();
    StringTokenizer st = new StringTokenizer(thisLine);
    st.nextToken();
    String gateway = st.nextToken();
    System.out.printf("The gateway is %s\n", gateway);
}
}

Courtesy of Chris Bunch from: How can I determine the IP of my router/gateway in Java?

Greets!

Community
  • 1
  • 1
N30
  • 53
  • 8
  • Not really... what if you're two (or some unknown number of) hops from the external gateway? – Jim Garrison Apr 11 '14 at 22:13
  • the perfect solution is from the link mentioned by N30. it searchs the Ip address from "whatismyip" html code based on regular expression. to be honest it's a genius solution Regards! – hannibal Apr 11 '14 at 22:38