I have setup a web service in my android device. Now I want to send request to android from a pc through WiFi. I need the ip address of my android device to access it from a pc in the same network. How will I find the IP through my code?
Can anyone help me?
Thanks in advance..
To get device ip address use this method:
public String getLocalIpAddress() {
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.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
if this method returns null, there is no connection available.
If the method returns a string, this string contains the ip address currently used by the device independent of 3G or WiFi.
Just found how to get your internal IP:
Settings >> Wireless Controls >> Wi-Fi Settings
At the bottom under "Wi-Fi networks"
tap the connection you are connected to
It brings up a window with info like:
Status
Speed
Signal Strength
Security
**IP Address**
Related
My pc is connected to 2 different interfaces that make access to the internet possible (a wired connection and a wifi connection to my smartphone that has mobile access, to be used in case the wired connection is lost).
When the wired connection has internet connection, I manually disconnect the other (mobile) connection at the DOS prompt :
netsh wlan disconnect interface="Wi-Fi"
Now i will check every minute or so if i can reach whatever site through the wired internet connection.
As soon as this fails, java will connect to the Wi-Fi connection again so that the loss of internet connection is minimal :
But here comes my problem : as soon as the wired internet is up and running again, I want java to automatically connect through that interface address again and disconnect the "Wi-Fi" (to limit costs ...).
I don't know if it is possible to connect to a URL starting with a predefined IP address in order to find out when the wired connection is online again.
Finally i found a solution myself, as illustrated in following code (this code runs as a test, start it on a desktop with both a wired and a wifi connection, which automatically results in closing the mobile connection, then manually disconnect the wired connection which automatically opens the mobile connection again. As soon as you manually reconnect the wired connection, the mobile connection will be disconnected again).
package testingPackage;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.Enumeration;
public class TestInternet {
public static void main(String[] args) {
int internet = 1;
int counter = 0;
while(counter<10){
counter = counter + 1;
int connections = 0;
Socket[] soc = new Socket[10];
try{
NetworkInterface nif = NetworkInterface.getByName("eth1");
//the right name of the wired internet can be found with following code in between /* … */
/*
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback()) {
List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
InterfaceAddress adr = iter.next();
InetAddress inadr = adr.getAddress();
if (inadr instanceof Inet4Address){
NetworkInterface nif1 = NetworkInterface.getByInetAddress(inadr);
System.out.println("L30 = "+nif1);
}
}
}
}
*/
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
while (nifAddresses.hasMoreElements()){
soc[connections] = new java.net.Socket();
soc[connections].bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
connections = connections + 1;
}
soc[0].connect(new InetSocketAddress("www.google.com", 80));
if(internet==0){
System.out.println("Internet is BACK, throw out the mobile internet now !");
try{
Runtime.getRuntime().exec(new String[]{"netsh", "wlan", "disconnect", "interface=Wi-Fi"});
internet = 1;
}
catch (Exception e2) {System.out.println("Warning : Could not disconnect the mobile network !"); }
}
else{
System.out.println("Internet is UP");
}
}
catch (Exception e) {
System.out.println("enumeration failed");connections = 0;
System.out.println("Internet is still DOWN, connect to mobile internet now !");
connections = 0;
internet = 0;
//find SSID name, profile name and interface name of the wired and wireless network in DOS :
//netsh wlan show networks : returns the SSID name XXXX
//netsh wlan show profile (REQUIRED): returns the profile name YYYY
//netsh wlan show interfaces : returns the interface name
try{
Runtime.getRuntime().exec(new String[]{"netsh", "wlan", "connect","ssid=XXXX", "name=YYYY", "interface=Wi-Fi"});
}
catch (Exception e2) {System.out.println("Warning : no internet ! Could not connect to mobile network !"); }
}
System.out.println("number of wired connections = "+connections);
try {Thread.sleep(10000);}
catch (InterruptedException e) {System.out.println("no sleep"); }
}
}
}
Alright, so I adapted the code from http://enigma2eureka.blogspot.com/2009/08/finding-your-ip-v4-broadcast-address.html in an attempt to find the IP address of the Broadcast Address on my Wi-Fi Router.
protected static InetAddress getBroadcastAddress() throws SocketException {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
System.out.println(networkInterface.toString() + networkInterface.getInterfaceAddresses());
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback interface
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null)
continue;
return broadcast;
}
}
return null;
}
However, it prints the following - the name and the list of interface addresses:
name:lo (Software Loopback Interface 1)[/127.0.0.1/8 [/127.255.255.255]]
name:eth0 (Microsoft Kernel Debug Network Adapter)[]
name:net0 (Belkin USB Wireless Adaptor)[null]
...
The Belkin adapter - net0 - seems to have a null broadcast address, although it shouldn't. (I did remember to set the prefer IPv4 system property) Can anyone identify why it returns null?
I am trying to connect android device with laptop or desktop which contains Bluetooth via Bluetooth socket connection.
I have created one android application (Client) which tries to connect laptop Bluetooth device where java application (Server) is running.
My concern is that, Is it possible to connect both the device insecurely (without pin authentication) using Bluetooth socket connection?
If possible, Please suggest me solution.
If not, Is there any way to programmatically auto pair both the devices?
Thanks in advance !!!
By referring java api for bluetooth, I got the solution for Insecure connection between two Android and laptop Bluetooth devices.
I have used SPP client server mechanism.
My server is in java.
In java add certain parameters to URL.
Make authentication= false; authorize=false;encrypt=false;
open this URL for connection acceptance.
//Create a UUID for SPP
UUID uuid=new UUID("0f2b61c18be240e6ab90e735818da0a7", false);
System.out.println("\n"+uuid.toString());
//Create the servicve url
String url="btspp://localhost:"+uuid.toString()+";"+"name=remoteNotifier;authenticate=false;authorize=false;encrypt=false";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open(url);
//Create a UUID for SPP
UUID uuid=new UUID("0f2b61c18be240e6ab90e735818da0a7", false);
System.out.println("\n"+uuid.toString());
//Create the servicve url
String url="btspp://localhost:"+uuid.toString()+";"+"name=remoteNotifier;authenticate=false;authorize=false;encrypt=false";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open(url);
Now on client side:
Android API 10 above contains insecure connection method. "createInsecureRfcommSocketToServiceRecord(UUID)"
So use this method for connection. It will not pop up for pairing request adn try to connect with remote Bluetooth device where Java server is already running.
Code:
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
// btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
mBluetoothAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android_logo);
// byte[] msgBuffer = getBytesFromBitmap(bitmap);
String message = "Hello from Android.\n";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00")) {
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
}
// AlertBox("Fatal Error", msg);
}
I have provided only required code.
For connection UUID should be same for both the devices.
Provide server Bluetooth MAC address at "address" field at client side.
We are able to communicate with remote Bluetooth device insecurely (Without pairing).
But this code is device dependent...
certain device are able to communicate very efficiently.
Like Lenovo laptop, external bluetooth device for PC for Java server
AND
Android devices DELL venue 7, Sony, LG mobiles for client.
Tested and working properly.
But in Dell laptop, Micromaxx, xolo mobile it doesn't work.
I don't know why it is not working, If anyone knows please give the solution.
For Bluetooth 2.1 and above devices, security is mandatory.
If you are just trying to avoid the passkey entry/display, you can set the security requirements on the laptop and android device to "MITM protection not required".
This way the devices will pair automatically, but the link would be susceptible to man in the middle attacks.
I'm trying to connect a client android to a app server java, but no work. This is code:
Android client;
_cb_led1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Socket mySocket = new Socket("127.0.0.1", 9090);
PrintStream p = new PrintStream(mySocket.getOutputStream());
p.println("Mensaje");
}
});
Java Server:
s = new ServerSocket(9090);
sc = s.accept();
System.out.println("Conexión establecida");
b = new BufferedReader( new InputStreamReader ( sc.getInputStream() ) );
while ( true )
{
mensaje = b.readLine();
System.out.println(mensaje);
}
b.close();
sc.close();
s.close();
}
catch (IOException e)
{
System.out.println("No puedo crear el socket");
}
}
any suggestions
thank you very much
127.0.0.1 points to localhost on the emulator. You have to either use the actual ip address of your computer or 10.0.2.2 which points to localhost on the computer running the emulator.
127.0.0.1 means "this machine". Is the server really on the same Android device (or emulator)?
If it is, why bother with socket connections? If it's not, please specify a real address or name.
From the standpoint of the Android emulator, the computer it's hosted on is not the same machine. If that's where the server is running, use its publicly available IP address.
When I am connected to WiFi, I can obtain the IP address of the Android phone.
However, when on the mobile network like 3G connection, is it still possible to obtain the IP address of the Android phone?
If yes, kindly post the code for the same.
try something like this
String ipAddress = null;
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.isLoopbackAddress()) {
ipAddress = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {}
the mobile device does not have an ip when browsing over 3G connection, You will get the ISP ip on the server side code. I recommend you replace the ip with the unique id, device type and coordinates if possible.