Obtain the local IP address and MAC address in Android
Use InetAddress. getLocalHost () to obtain "127.0.0.1". To obtain a real network IP address, use the following method:
First, create a project and modify the AndroidManifest. xml file to add user permissions, as shown below:
// Required
// Required
The main function code is as follows:
// Obtain the local IP Address
Public String getLocalHostIp ()
{
String ipaddress = "";
Try
{
Enumeration En = NetworkInterface
. GetNetworkInterfaces ();
// Traverse the network interface used
While (en. hasMoreElements ())
{
NetworkInterface nif = en. nextElement (); // obtain all ip addresses bound to each network interface
Enumeration Inet = nif. getInetAddresses ();
// Traverse all ip addresses bound to each interface
While (inet. hasMoreElements ())
{
InetAddress ip = inet. nextElement ();
If (! Ip. isLoopbackAddress ()
& InetAddressUtils. is%4address (ip
. GetHostAddress ()))
{
Return ipaddress = "the ip address of the local machine is" + ":" + ip. getHostAddress ();
}
}
}
}
Catch (SocketException e)
{
Log. e ("feige", "failed to obtain local IP Address ");
E. printStackTrace ();
}
Return ipaddress;
}
// Obtain the Mac address of the Local Machine
Public String getLocalMac ()
{
String mac = "";
// Obtain the wifi Manager
WifiManager wifiMng = (WifiManager) getSystemService (Context. WIFI_SERVICE );
WifiInfo wifiInfor = wifiMng. getConnectionInfo ();
Mac = "the mac address of the local machine is:" + wifiInfor. getMacAddress ();
Return mac;
}