Android access to WiFi extranet IP method

Source: Internet
Author: User
Tags get ip readline

android Get WiFi extranet IP method

  Get extranet ip   public static string getnetip ()  {        URL infoUrl = null;       inputstream instream =  null;       try {            // http://iframe.ip138.com/ic.asp             infourl = new url ("http://city.ip138.com/city0.asp");            infourl = new url ("http://ip38.com");            urlconnection connection = infourl.openconnection ();            HttpURLConnection httpConnection =  ( HttpURLConnection)  connection;           int  Responsecode = httPconnection.getresponsecode ();           if  ( RESPONSECODE == HTTPURLCONNECTION.HTTP_OK)  {                instream = httpconnection.getinputstream ();                bufferedreader reader = new  bufferedreader (                        new inputstreamreader (instream,  "Utf-8"));                stringbuilder strber =  new stringbuilder ();                String line = null;                while  (line&Nbsp;= reader.readline ())  != null                     strber.append (line +  "\ n");                instream.close ();                //  Extract IP address        from feedback results          // int start = strber.indexof ("[");                // log.d ("Zph",  ""  + start);               //  int end = strber.indexof ("]",  start + 1);                // LOG.D ("zph",  ""  + end);      &NBSp;         line = strber.substring (378, 395);                line.replaceall (" ",   "");               return line ;           }       } catch   (malformedurlexception e)  {            E.printstacktrace ();       } catch  (ioexception e)  {            e.printstacktrace ();        }       return null;  }


Another high-end way to get extranet IP

Public static string getnetip ()    {   string ip =  "";    try   {   string address =  "http://ip.taobao.com/service/getIpInfo2.php ? Ip=myip ";   url url = new url (address);   httpurlconnection 
connection =  (httpurlconnection)  url   openconnection ();   Connection.setusecaches (False);      if  (Connection.getresponsecode ()  ==  HTTPURLCONNECTION.HTTP_OK)    {   Inputstream in = connection.getinputstream () ;     //  will be converted to strings    bufferedreader reader = new  BufferedReader (   New inputstreamreader (in));      string tmpstring  =  "";   stringbuilder retjson = new stringbuilder ();   while  ( (Tmpstring = readeR.readline ())  != null)    {   retjson.append (tmpstring +  "\ n");   }      Jsonobject jsonobject = new jsonobject (retjson.tostring ());    string code = jsonobject.getstring ("code");   if  (Code.equals ("0"))    {   jsonobject data = jsonobject.getjsonobject ("Data");   IP  = data.getstring ("IP")  +  "("  + data.getstring ("Country")    +  Data.getstring ("area")  +  "district"    + data.getstring ("region")  + data.getstring (" City ")    + data.getstring (" ISP ")  + ") ";      log.e (" Hint ", "
Your IP address is: " + ip";  }   else   {   ip =  "";   LOG.E ("Hint",  IP interface exception, cannot get IP address!) ");  }  }   else   {   ip =&nBSP; "";    LOG.E ("hint",  network connection exception, cannot get IP address!) ");  }  }   catch  (exception e)    {   IP =  "" ";   log.e (" Hint ", " an exception occurred while obtaining an IP address, the exception information is: " + e.tostring ());  }   return  IP;  }



Android access to wifi IP address

Wifimanager wifimanage= (Wifimanager) Context.getsystemservice (context.wifi_service);//Get WifiManager
//  Check to see if WiFi opens if
(!wifimanage.iswifienabled ()) {
wifimanage.setwifienabled (true);  
}
Wifiinfo wifiinfo= wifimanage.getconnectioninfo ();
String Ip=inttoip (Wifiinfo.getipaddress ());  
//convert the obtained int to a real IP address, refer to the Web, modify the next
private String inttoip (int i) {return
(I & 0xFF) + "." + ((I >> 8) & 0xFF)? + "." + ((I >>) & 0xFF) + "." + ((i >>) & 0xFF);



OK, is that good? Oh, don't forget to add permission


<uses-permission= "" Android:name= "Android.permission.ACCESS_WIFI_STATE" ></uses>
<uses- permission= "" Android:name= "Adnroid.permission.CHANGE_WIFI_STATE" ></use



Android development gets wifi and wired IP addresses

Set Permissions First:

<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE" ></uses-permission>
< Uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" ></uses-permission>
< Uses-permission android:name= "Android.permission.WAKE_LOCK" ></uses-permission>
/**  * if  (Intf.getname (). toLowerCase (). Equals ("eth0")  | |  intf.getname (). toLowerCase (). Equals ("Wlan0"))   *  says: Only filters for wireless and wired ip. networkinterface have a lot of names   *  such as SIM0,REMT1 ... And so on. I don't need it.   *   * if  (!ipaddress.contains ("::"))    *  represents:  Filter out the address of the IPv6. Both wireless and cable   have this address,  *  my side. The address is generally: fe80::288:88ff:fe00:1%eth0 fe80::ee17:2fff:fece: c0b4%wlan0  *  are generally present in the first cycle. The second cycle is the real IPv4 address .  *   *  @return   *  @throws  SocketException  */   public string getipaddress ()  throws  socketexception {   string ipaddress =  "";   Enumeration< networkinterface> netinterfaces = null;   try {   netInterfaces  = networkinterface.getnetworkinterfaces ();   while  (netinterfaces.hasmoreelements ())  {    NETWORKINTERFACE&NBSp;intf = netinterfaces.nextelement ();   if  (Intf.getname (). ToLowerCase (). Equals ("eth0 ")  | | intf.getname (). toLowerCase (). Equals (" Wlan0 "))  {   for  (enumeration <inetaddress> enumipaddr = intf.getinetaddresses ()  enumipaddr.hasmoreelements ();)  {   inetaddress inetaddress = enumipaddr.nextelement ();   if  (! Inetaddress.isloopbackaddress ())  {   ipaddress = inetaddress.gethostaddress (). toString ();   if  (!ipaddress.contains ("::")  {// ipv6 address    ipaddress =  ipaddress;  }  }  }  } else {   continue;   }  }  } catch  (exception e)  {   e.printstacktrace ();   }  // final contentresolver mcontentresolver =  Getcontentresolver ();  // settings.system.putint ( mContentResolver,  // settings.system.wifi_use_ static_ip, 1);  // settings.system.putstring ( mContentResolver,  //  settings.system.wifi_static_ip,  "Your IP address";      return ipaddress;  }          public string getaddress ()  {   wifimanager  wifimanager =  (Wifimanager)  getactivity (). Getsystemservice (Context.wifi_service);  //
  Determine if WiFi is open    if  (!wifimanager.iswifienabled ())  {   Wifimanager.setwifienabled (True);  }   wifiinfo wifiinfo =  Wifimanager.getconnectioninfo ();   dhcpinfo info = wifimanager.getdhcpinfo ();    int ipaddress = wifiinfo.getipaddress ();   int ii =  info.ipaddress;  // return inttoip (ipaddrESS);   return ipaddress +  "    dhcp: "  + ii;      }         Private string inttoip (int i)  {    return  (I & 0xff)  +  "."  +   ((i >> 8)  & 0xff)  +  "."  +   ((i >> 16)  & 0xff)  +  "."  +   (I&NBSP;&GT;&GT;&NBSP;24&NBSP;&AMP;&NBSP;0XFF);  }  }


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.