Using InetAddress to get own IP - java

I have an issue were if I try to InetAddress.getLocalHost() or even InetAddress.getByName(String host) it throws an exception every time even for a known website like nba.com I am a bit confused FYI the target device is an android 4.1.1 GS3 and wifi and mobile network are on. Code below
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my Android := "+ownIP.getHostAddress());
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
String t = e.getMessage() + "yes";
}
Below is the System.out
03-12 18:59:52.636: I/System.out(18996): Exception caught =null
Thanks in advance

I use a tricky method to get my own IP. you can see whether it helps you
String getIP() {
try {
Socket socket = new Socket("google.com", 80);
return socket.getLocalAddress().getHostAddress();
} catch (Exception e) {
}
}

I believe I have found out what my issue was basically I guess you are not allowed to perform any network operations in the Main thread for android this was optional before and is now required for Honeycomb (API 11) and up below is the comment as per google specs.
"To prevent blocking the main user interface thread, Google recommends using the AsyncTask class from the android.os package:"
So all I was create a new class NetTask which extends AsyncTask and perform all network applications so now my code is working. IDK if everybody else knew that but I figured I would post this in case any newbs like me were still looking for a solution :) !!!
Thanks

Related

How to fix "java.io.IOException: read failed, socket might closed or timeout" when trying to connect to a paired device?

I've made a ListView with devices currently paired to my phone so that I can select one of them and connect to it. To determine which device was selected, I'm storing their MAC Addresses in an array so that I can get a device by its address. When I select a device, the app freezes for a bit then restores with no success of connecting. I cannot find the solution anywhere and I'm stuck. I'm still a beginner and do not understand much. An exception occurs that goes like:
java.io.IOException: read failed, socket might be closed or timeout, read ret: -1
Here is my code.
// If the UUID is incorrect then this one does not work as well
// 00001101-0000-1000-8000-00805f9b34fb
private static final UUID CONNECTION_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
public static boolean connectDevice(final int a) {
try {
BluetoothDevice mBluetoothDevice = btAdapter.getRemoteDevice(deviceAddress[a]);
BluetoothSocket mBluetoothSocket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(CONNECTION_UUID);
btAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mmOutputStream = new DataOutputStream(mBluetoothSocket.getOutputStream());
mmInputStream = new DataInputStream(mBluetoothSocket.getInputStream());
mBluetoothSocket.close();
} catch (NullPointerException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
From the CONNECTION_UUID that you provided in your code, I assume that you are connecting with a Bluetooth serial board. I am not sure about the problem yet, however, I thought of writing this answer to provide a probable solution that might solve your issue.
I think in case of the paired devices, you need to initiate the connection with a secure channel. Currently, you are using an insecure channel.
From the documentation...
The communication channel will not have an authenticated link key i.e
it will be subject to man-in-the-middle attacks. For Bluetooth 2.1
devices, the link key will be encrypted, as encryption is mandatory.
For legacy devices (pre Bluetooth 2.1 devices) the link key will be
not be encrypted. Use createRfcommSocketToServiceRecord(UUID) if an
encrypted and authenticated communication channel is desired.
Hence you might consider using createRfcommSocketToServiceRecord() for your case.
Instead of this
BluetoothSocket mBluetoothSocket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(CONNECTION_UUID);
Use this...
BluetoothSocket mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(CONNECTION_UUID);
I hope that solves your problem.
From the comment below - The UUID that actually worked here is 00001101-0000-1000-8000-00805f9b34fb

IntelliJ: Why java.net.InetAddress is deprecated Class?

I've got a some problem. My program cant't run, throws: nullPointException. On other IDE it's running.
One day ago I just click something, I don't know what that was :(
Now this is look like this:
InetAddress localHost = Inet4Address.getLocalHost();
But InetAddress is strike throuh.
Please help, how can I undo this.
This method is not deprecated in the version up to Java 9
https://docs.oracle.com/javase/9/docs/api/java/net/InetAddress.html#getLocalHost--
I have seen this fail on mis-configured machines. e.g. you have an invalid hosts file, though it shouldn't ever throw a NullPointerException AFAIK.
What I do is catch UnknownHostException and use "localhost" instead if this fails.
https://github.com/OpenHFT/Chronicle-Core/blob/master/src/main/java/net/openhft/chronicle/core/OS.java#L133
private static String getHostName0() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}

How to handle data roaming when you use sockets in Android?

I'm programming a game in Android that uses AI, which requires big CPU power, that a normal Android device just doesn't have. So I decided to write a server in Java using sockets that will calculate everything and return a value to the client (the android device).
Now, I'm used to program for PC, but not for phones. In mobile, the IP of the device can change back and forth due to data roaming and WIFI.
My question is, how do you handle a changing IP? How do you tell a new connection is the same device? Or maybe the Android device does all of that automatically?
I'm new to stackoverflow, I hope I didn't ask too many questions. :)
Thank you very much for your answers!
You don't need to handle ip changing at all. A client(an android device) must know server host/ip and reconnect if it was disconnected from network, nothing more.
private static class ConnectionTask implements Runnable {
private boolean connected;
#Override public void run() {
try {
InetAddress serverAddress = InetAddress.getByName("host");
Socket socket = new Socket(serverAddress, 9999);
connected = true;
while (connected) {
// sending or writing data
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
//here you lost the connection due to some reason
//you need to notify user about the problem and wait for connection
}
}
}
To receive event about network state you need to register receiver:
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (isNetworkAvailable()) {
unregisterReceiver(this);
tryToConnect();
}
}
}, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
Okay guys I figured out a way, thank to Fox in socks' answer.
Each time a user connects to the server socket, you take his UUID (or an hashed version of it, if you want more security :P ).
Then, when that user disconnects for some reason and tries to connect to the server socket again, he'll send the same UUID. That way, you can tell both of the connections are the same, and continue with the processing.
For more information about UUID, look here:
Is there a unique Android device ID?
Thank you all! :)
Now how do I mark this question as a closed one? :P

Bluetooth Socket [isConnected()]

I have 3 activities that uses Bluetooth Connection/Communication.
On my first page, I connect to a bluetooth device already. When I move to another activity, I tried using this code:
BluetoothSocket btSocket;
try{
if(btSocket.isConnected(){
System.out.println("connected");
}
}
catch (Exception e{
}
I did not get anything in my Logcat at all and the Activity did not crash too. I'm not sure on how to use a Thread/Runnable for this Bluetooth Connection to stay in connection through activities and such. So I was thinking if this is possible?
Thanks.
Your current approach seem to fail with an NullPointerException, which will be catched by your Exception-Block. I would suggest you to implement a Background service which will handle the BT-connection in background. A sample could be found on the bottom of this page: http://developer.android.com/guide/topics/connectivity/bluetooth.html (Related Samples)
That is because you are ignoring the Exception that btSocket is null.
try
catch (Exception e{ e.printStackTrace ();
}
You will need to finad a way to pass you active Bluetooth connection to this method/activity.

Port in use by "Port currently not owned"

I'm getting some strange results from the javax.comm library. I'm running this constructor:
SerialPort port;
public Scale(String porttotry) {
CommPortIdentifier cpi = null;
try {
cpi = CommPortIdentifier.getPortIdentifier(porttotry);
//Open Port and establish stream
log.trace("Opening CPI: {}", cpi.getCurrentOwner());
port = (SerialPort) cpi.open("My Application", 2000);
log.trace("CPI opened");
//... configuration stuff
} catch (PortInUseException ex) {
log.error("{}: Port in use by {}", porttotry, cpi.getCurrentOwner());
} catch (NoSuchPortException ex) {
log.error("No such port as {}", porttotry);
}
}
What's really strange is the fact that CommPortIdentifier.open(String, int) appears to be throwing a PortInUseException when the port is not in use. The log output says
TRACE [10:19:03.147] Scale:72 Opening CPI: Port currently not owned
ERROR [10:19:05.149] Scale:98 COM4: Port in use by Port currently not owned
The first log line means to me that open() should succeed, but it doesn't. I've connected to this device before and gotten data from it. This is a strange new error. Does anybody have any idea what could cause this? My gut tells me that this is some tricky thing with Windows having possession issues. I'm open to any ideas and I'll provide more information if you need it.
I can't speak for exactly why this strange error occurred, but I did find something of a solution. It seems that I was correct in assuming it was Windows being possessive. When I shut down, unplugged my device, powered on with the device still unplugged, then connected the device, the PortInUseException disappeared.

Categories

Resources