how to get the client's IP? [duplicate] - java

This question already has answers here:
java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?
(11 answers)
Closed 7 years ago.
My code always return the loopback ip instead of my IP whick is 192.168..
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}

There are some websites, that their sole piece of data is one line, which includes your public IP address.
Try something like:
URLConnection con = new URL("http://www.myipaddress.com").openConnection();
String ip = new BufferedReader(new
InputStreamReader(con.getInputStream())).readLine();

Related

Java Socket Client Unable to Connect to C# Socket Server

I have a use case, where I have to send data from a .NET application, to a Java application and I'm trying to do this using sockets. I have a server created using C# -
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
Console.WriteLine("The server is running at port 13...");
Console.WriteLine("The local End point is -" +
tcpListener.LocalEndpoint);
output = "Waiting for a connection...";
Console.WriteLine(output);
Socket s = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
}
catch (Exception e)
{
output = "Error: " + e.ToString();
Console.WriteLine(output);
}
}
On the Java side, I have created a socket which listens to the same host and port -
Socket socket;
try {
socket = new Socket( "localhost", 13);
System.out.println("Connection established");
BufferedReader input =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
I'm getting the below error - java.net.ConnectException: Connection refused: connect. I have used telnet localhost 13, to check if my server is really running, and it is. So i don't think it could be an issue with server not running or firewalls, since both are running locally. Any ideas on how to resolve this?
I tried your code and I had exactly the same problem. Your C# TCP Server only binds to the IPv6 interface (check e.g. the resource monitor listening addresses). If you change your server to new TcpListener(IPAddress.Any, 13) it should work.

Android function to return IP address

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

Print to video Ip-address-from socket

I wish I could create a small application that I print screen the IP address to which the socket is connected.
I'm trying this code:
public void onClick(View v) {
Socket s = new Socket();
String host ="10.10.20.xxxx";
try {
s.connect( new InetSocketAddress( host, 6000 ), 1000 );
InetAddress inetAddress = s.getLocalAddress();
String ip = inetAddress.getHostAddress();
//Now, I would like to have printed out the IP-address
Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show();
//But nothing happens
} catch (IOException e) {
e.printStackTrace();
}
}
}
But, I have never seen printed the IP address,
If is necessary I can create a TextView and inside-It put the string ip.
Where am I doing wrong? Thanks!
ulyssessPax:
When you connect/accept to/from a device via TCP sockets, you have the following method from that socket:
socket.getRemoteSocketAddress().toString()
it gives you the remote IP address and the port number where it's connected. For example: 192.168.1.30:6000
socket.getLocalSocketAddress()
it gives you the local IP address and the port number where it has established the connection. For example: 10.0.2.15:54471
Hope it's what you're looking for.

Get non-local IP Address Java [duplicate]

This question already has answers here:
Getting the IP address of the current machine using Java
(19 answers)
Closed 9 years ago.
I have a program which requires it to know it's IP Address. However when I use
InetAddress current_addr = addresses.nextElement();
It returns
127.0.1.1
Which isn't very helpful. How can I get my non-local IP Address from java?
What do you get when you use:
InetAddress IP = InetAddress.getLocalHost();
String ipAddress = IP.getHostAddress();
it should ideally give you the ip address if you don't have more than one network interfaces.
I tested it locally and it gives me proper ip address of my machine i.e.
192.168.2.10
If you have more than one network interface then you can try to use the NetworkInterface class, here is the sample:
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
System.out.println("Interface: " + e.getName());
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
Source taken from a related post: java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?

How to get the IP address for remote host using Java

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

Categories

Resources