馬上加入Android 台灣中文網,立即免費下載應用遊戲。
您需要 登錄 才可以下載或查看,沒有帳號?註冊
x
本帖最後由 deep_dream 於 2011-12-16 11:21 編輯
我目前在開發Android相關的App...
想知道當手機連上網路之後(Wifi or 3G),通常會拿到一個IP,而這個IP通常都是由DHCP Server所配發下來的IP。
原理我想應該就跟一般的IP分享器 OR 無線基地台一樣。
我目前只知道由Wifi的方式來拿到DhcpInfo,不過也沒有Server Domain...
想知道有沒有任何寫過相關部分的前輩可以給我一點意見~~~
以下為我測試的程式~- public class DhcpClientActivity extends Activity {
- /** Called when the activity is first created. */
- private TextView textViewRes;
- private Button button01;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textViewRes = (TextView) findViewById(R.id.textViewRes);
- button01 = (Button) findViewById(R.id.button01);
- button01.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // TODO Auto-generated method stub
- WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
- DhcpInfo d = wifiMgr.getDhcpInfo();
- String s_dns1 = "";
- String s_dns2 = "";
- String s_gateway = "";
- String s_ipAddress = "";
- String s_leaseDuration = "";
- String s_netmask = "";
- String s_serverAddress = "";
-
- s_dns1 = "DNS 1: " + intToIp(d.dns1);
- s_dns2 = "DNS 2: " + intToIp(d.dns2);
- s_gateway = "Default Gateway: " + intToIp(d.gateway);
- s_ipAddress = "IP Address: " + intToIp(d.ipAddress);
- s_leaseDuration = "Lease Time: " + String.valueOf(d.leaseDuration);
- s_netmask = "Subnet Mask: " + intToIp(d.netmask);
- s_serverAddress = "Server IP: " + intToIp(d.serverAddress);
- textViewRes.setText("Network Info\n" + s_dns1 + "\n" + s_dns2
- + "\n" + s_gateway + "\n" + s_ipAddress + "\n"
- + s_leaseDuration + "\n" + s_netmask + "\n"
- + s_serverAddress);
- }
- });
- }
- public String intToIp(int i) {
- return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
- + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
- }
- }
複製代碼 奇怪的還有一件事,拿到的IP都是反的,可是我覺得String intToIp(int i)裡面的操作應該是正確的才對。
假設拿到的ip是192.168.1.1
那麼就是
-----byte1-----,-----byte2-----,-----byte3-----,-----byte4-----
11000000 , 10101000 , 00000001 , 00000001
經過運算之後轉成的才對。
不過我實際上拿到的都是1.1.168.192…這點讓人很不解… |