Created
February 27, 2013 09:57
-
-
Save myamamic/5046776 to your computer and use it in GitHub Desktop.
[android] IPアドレス取得
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// モバイルネットワークインターフェースのIPアドレスを取得する。 | |
// 注意:インターフェース2つとか、もろもろの異常系は考慮していない | |
private static final String LOCAL_LOOPBACK_ADDR = "127.0.0.1"; | |
private static final String INVALID_ADDR = "0.0.0.0"; | |
private static String getMobileIPAddress() { | |
try { | |
NetworkInterface ni = NetworkInterface.getByName("hso0"); // インターフェース名 | |
if (ni == null) { | |
Log.d(TAG, "Failed to get mobile interface."); | |
return null; | |
} | |
Enumeration<InetAddress> addresses = ni.getInetAddresses(); | |
while (addresses.hasMoreElements()) { | |
String address = addresses.nextElement().getHostAddress(); | |
if (!LOCAL_LOOPBACK_ADDR.equals(address) && !INVALID_ADDR.equals(address)) { | |
// Found valid ip address. | |
return address; | |
} | |
} | |
return null; | |
} catch (Exception e) { | |
Log.d(TAG, "Exception occured. e=" + e.getMessage()); | |
return null; | |
} | |
} | |
// Wi-FiインターフェースのIPアドレスを取得する。 | |
// 注意:インターフェース2つとか、もろもろの異常系は考慮していない | |
private static String getWifiIPAddress(Context context) { | |
WifiManager manager = (WifiManager)context.getSystemService(WIFI_SERVICE); | |
WifiInfo info = manager.getConnectionInfo(); | |
int ipAddr = info.getIpAddress(); | |
String ipString = String.format("%02d.%02d.%02d.%02d", | |
(ipAddr>>0)&0xff, (ipAddr>>8)&0xff, (ipAddr>>16)&0xff, (ipAddr>>24)&0xff); | |
return ipString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment