I have a java spring MVC web application, I am trying to get the IP address of the client machine who are accessing the application.I had tried the code shown below,
InetAddress addr = InetAddress.getLocalHost();
String ipAddr = addr.getHostAddress();
But this is returning me the IP address of localhost.
I have also tried few other suggestions found online like the one below:
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
}
This is also not giving the right IP address. I have also tried the following and nothing has worked for me:
https://www.mkyong.com/java/how-to-get-client-ip-address-in-java/
what is the right way to get request's ip
Nothing is giving me the correct IP address. Is there any solution that I could try to get the correct IP address of the machine that is accessing my application.
You have to read the request from where request is coming, Try this
public void readIp(HttpServletRequest request,HttpServletResponse response){
String ip = request.getRemoteAddr();
System.out.println("ip: "+ip);
}
Related
I'm developing one socket app.
Background :
There is two android device.
Both device is on different network (i.e. one is on mobilenetwork and other is on different mobile network or on wifi).
App is working good when on same wifi network.
App is not working on different network.
I've read about port forwarding but this all ended up with router port forwarding, so this has nothing to do with my app, as my app is like to work on different network.
What I've tried:
Use Socket-communication over different networks [ Still unable to find the answer]
I got server ip address using following method and it gives me ip address:
public String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "Server running at : "
+ inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
text.setText(ip);
return ip;
}
I'm using static port 8080 [May be this is a problem,please suggest me a option if so].
I'm using this lines at client side to connect but soket object returns null on different network:
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
So,Please suggest me what should i use for communicating over
different real android device with different network [app runs on same
network perfectly]?
https://en.wikipedia.org/wiki/TCP_hole_punching
This technique can be used if you're attached to P2P connectivity.
Otherwise, you can get an online server that is accessible to both clients and it can be used to forward messages between the two. Amazon Web Services is a good option for this, you can get one year free trial with a T2.mini machine with a public IP.
https://aws.amazon.com/
I'm sending data from android device to localhost database. To do this I need to use my ip address. I can find my ip address by searching 'ipconfig' on the command prompt. I just noticed that my ip address changed slightly even though im using the same wifi connection. The last digit of my ip address changed. This needed a minor change in my code but I was wonder if there was an android function that returned your computers ip address for you so that the code could look like below. Such a function would also help when using other forms of internet connection that would change your ip address.
HttpPost httpPost = new HttpPost("http://" + ipAddressFunction() + "/linker.php");// home wifi
first get your network-interfaces via:
NetworkInterface.getNetworkInterfaces();
then get the IP(s) va:
getInetAddresses()
Here is a function i made to get my Android Device IP.
//Get The Local IP Addresses
private String GetLocalIPAddress(Boolean LoopBack)
{
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement ();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement ();
if(inetAddress.getHostAddress().contains("."))
{
if(inetAddress.isLoopbackAddress() == LoopBack)
{
return inetAddress.getHostAddress();
}
}
}
}
}
catch (Exception e)
{
Log.d(this.getClass().toString(), "Failed Getting Local IP\n\n" + e.getMessage());
}
return null;
}
This function receives a Boolean parameter, if True, it will return the Local Loopback IP (I.E: 127.0.0.1), if False, it will return the normal IP (I.E: 192.168.0.5)
You can try to connect multiple IP, if have the return data is proved to be a computer IP
I'm developing a REST API, in some cases i want to make sure a request came from a known ip that set in a backend UI.
I tried this:
try {
URL url = new URL(allowedHostname);
InetAddress[] allowedIps = InetAddress.getAllByName(url.getHost());
for (InetAddress host : allowedIps) {
if (requesterIp.equals(host.getHostAddress())) {
return true;
}
}
} catch (UnknownHostException e) {
logger.warn("[validateHostname] ", e);
}
return false;
Where allowedHostname = request.getRemoteAddr()
But it doesn't seems to work.
i do not want just to validate the hostname, because it is relatively easy to make requests in the name of another host.
Edit
requesterIp = request.getRemoteAddr()
allowedHostname = a predefined url set in backend UI
Your serlvet container or appserver is most likely behind a proxy. To get the correct address you'll need to configure the proxy to forward the remote ip address.
http://docs.oracle.com/javaee/5/api/javax/servlet/ServletRequest.html
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.
I need to get the IP address for remote hosts. I tried the following and works fine:
socket = factory.createSocket(hostName, port);
InetAddress remoteIP = socket.getInetAddress();
String[] remoteIPOnly = remoteIP.toString().split("\\/");
System.out.println("Remote IP is: "+remoteIPOnly[1]);
But, I need a way where I don't have to specify a port number. I.e, I need the IP for a remote host despite the port number. Is this possible ? Is it possible to get the IP without creating socket from the first place ?
Try this:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
byte[] raw = inetAddress.getAddress();
The byte array now contains the IP addresses bytes.
Use getHostAddress() as below:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
String ipAddress = inetAddress.getHostAddress();
System.out.println(ipAddress );//prints 66.152.109.61
I am trying to send a message to a server and get the response.
When i try to open a socket I get an exception :
I have added to AndroidManifest.xml the following lines:
< uses-permission android:name="android.permission.INTERNET" />
< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Before the application tags.
Here is the code i have:
String IP = "81.218.150.49";
int port = 32001;
Socket my_socket = new Socket(IP, port); //Here i get exception !!
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(my_socket.getOutputStream(), "UTF8"));
wr.write("mobiwize server login test testpswd\r\n");
// Send data
wr.flush();
// Get response
StringBuffer sb = new StringBuffer("");
BufferedReader rd = new BufferedReader(new InputStreamReader(my_socket.getInputStream()));
String line ="";
String NL = System.getProperty("line.separator");
while ((line = rd.readLine()) != null) {
sb.append(line + NL);
}
httpStuff.setText(sb);
rd.close();
wr.close();
} catch (Exception e) {
}
I would really thank for any help!
Try this....
1. If you want to access this Server
with IP: 81.218.150.49 through Internet, then it must
be your static ip, rather than an dynamic one.
2. Try to run this code with a private ip address or public ip address which is assigned to your pc in LAN (ie. Without internet..JUST WITH WIRELESS CONNECTION).
3. Private ip or Public IP has No meaning until you are on INTERNET.. TILL THEN YOU CAN USE BOTH, AS ITS LAN.
4. Private ip ranges
Class A : 10.0.0.0 - 10.0.0.255
Class B : 172.16.0.0 - 172.31.255.255
Class C : 192.168.0.0 - 192.168.255.255
5. Public is given by your service provider, which will be anyone OUT of the private ip range. If your ip is not static, there is hardly or none of your chances to access the server over internet, there are sites that gives static ip out of your dynamic ips.
I had the same issue when used in Android while it was running fine in J2ee Java program, I suggest you to use a method call for this new socket thing, use the same code. Hopefully it will help coz it did to me ..
I suspect you got security error. The IP address you listed does not allow you to make the socket connection. Try another IP that you know your computer can make connections with. Test the IP for security with FTP, rlogin, or something.
I assume you're not trying to hack someone's PC or iMac :-)