Obtain the local IP address and MAC address in Android

Source: Internet
Author: User

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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.