Reputation: 1164
I am trying to get the ip address of my device but all in vain and no success. I've tried
public String getP2PIpAddr() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_P2P_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return ipString;
}
but its giving me 0.0.0.0 and no other method is working too..Help !!
Upvotes: 9
Views: 12099
Reputation: 1557
public static String getIpAddress() {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
/*
* for (NetworkInterface networkInterface : interfaces) { Log.v(TAG,
* "interface name " + networkInterface.getName() + "mac = " +
* getMACAddress(networkInterface.getName())); }
*/
for (NetworkInterface intf : interfaces) {
if (!getMACAddress(intf.getName()).equalsIgnoreCase(
Globals.thisDeviceAddress)) {
// Log.v(TAG, "ignore the interface " + intf.getName());
// continue;
}
if (!intf.getName().contains("p2p"))
continue;
Log.v(TAG,
intf.getName() + " " + getMACAddress(intf.getName()));
List<InetAddress> addrs = Collections.list(intf
.getInetAddresses());
for (InetAddress addr : addrs) {
// Log.v(TAG, "inside");
if (!addr.isLoopbackAddress()) {
// Log.v(TAG, "isnt loopback");
String sAddr = addr.getHostAddress().toUpperCase();
Log.v(TAG, "ip=" + sAddr);
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (isIPv4) {
if (sAddr.contains("192.168.49.")) {
Log.v(TAG, "ip = " + sAddr);
return sAddr;
}
}
}
}
}
} catch (Exception ex) {
Log.v(TAG, "error in parsing");
} // for now eat exceptions
Log.v(TAG, "returning empty ip address");
return "";
}
public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName))
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null)
return "";
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length() > 0)
buf.deleteCharAt(buf.length() - 1);
return buf.toString();
}
} catch (Exception ex) {
} // for now eat exceptions
return "";
/*
* try { // this is so Linux hack return
* loadFileAsString("/sys/class/net/" +interfaceName +
* "/address").toUpperCase().trim(); } catch (IOException ex) { return
* null; }
*/
}
Upvotes: 4
Reputation: 39846
Just as reference: I'm the developer of the WiFi-Shoot (a direct file transfer app via WiFi Direct).
Unfortunately, there's no way to get your own IP address, and the general principle of operation is slightly different:
initialize
to get a Channel, all other operations needs this channel.discoverPeers
and connect
to one of themrequestGroupInfo
that will tell you if that device is the group owner and what is the group owner IP address. So non-owners can connect to the owner using the supplied address and the owner will listen to connections.requestPeers
that will give you a list of all connected peers. That includes MAC addresses and names.The call Context.getSystemService(Context.WIFI_P2P_SERVICE)
will give you a WiFiP2PManager.
And yes, you'll need a bunch of WiFI permission such as ACCESS_WIFI_STATE
, CHANGE_WIFI_STATE
among others.
Upvotes: 12
Reputation: 1746
Firstly, check manifest file for permissions:
<uses-permission
android:required="true"
android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
android:required="true"
android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission
android:required="true"
android:name="android.permission.INTERNET"/>
Then, define what's IP looking for. If you want to broadcast that IP for purpose beyond the service discovering, find it by using WIFI_SERVICE. If you are curious about the ip address of your service broadcasting, NsdServiceInfo instance has getHost() method.
Upvotes: 0
Reputation: 7804
Use this code
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);
And add the permission to your manifest.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Upvotes: -1
Reputation: 1425
send out the peer's local ip address (starting with 192.168.x.x) to the group owner. After this "handshake", which doesn't really take time, it's all good to go. Did not find any other way to get the peer's ip addresses, the only information provided by GroupListener/PeerListener/... is the mac address.
Upvotes: 7
Reputation: 3596
If you are trying to get IP address of other device connected to WiFi network
try {
Address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Address);
Getting Internet IP address i.e live IP address
String myUrl = "http://api.externalip.net/ip";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try{
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity ht = httpResponse.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String ipaddress = r.readLine();
Toast.makeText(getApplicationContext(),"Live IP : " + ipaddress, Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
For more deeper knowledge and other native methods fallow link
http://developer.android.com/guide/topics/connectivity/wifip2p.html
Upvotes: 0
Reputation: 12748
Do you have permissions on the WiFi settings attached to your Android program manifest? At least ACCESS_WIFI_STATE
is needed [1]. If that is not enough, probably ACCESS_NETWORK_STATE
is also needed [2]. I did not find anything bad on your code, so trying to play with Manifest would be my suggestion.
The first link I have as source has in the accepted answer also INTERNET
permission, so that your program can also contact somewhere to ask for connection and thus IP. That would be the next permission to try, if the two first don't work.
You asked about official or credible sources, these are from the credible ones. Every peace of information is voted up on Stackoverflow at least once, and that if something says that these stuff have made it at least for someone.
My sources:
[1] How to get IP address of the device from code?
[2] Android WifiManager getConnectionInfo requires CHANGE_WIFI_STATE?
Upvotes: 0