2014-03-04 61 views
-1

我是Android編程的初學者。我想用這個方法:如何使用Socket方法?

Socket socket; 
socket.getInetAddress() ; 

我想在一個TextView IP地址打印到我連接的。 這可能嗎?我應該怎麼做?

謝謝!

我想這一點,但沒有工作

public void onClick(View v) { 

    Socket s = new Socket(); 
    String host ="10.10.20.xxxx"; 

try { 
    s.connect(new InetSocketAddress(host, 6000), 1000); 

    InetAddress inetAddress = s.getLocalAddress(); 
    String ip = inetAddress.getHostAddress(); 
    //Now, I would like to have printed out the IP-address 
    Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show(); 
//But nothing happens 
} catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 
} 
+1

您能向我們展示您已經嘗試過的嗎? –

+0

感謝Philippe的編輯,我更新了我的問題。 – ulyssessPax

+0

你是否能夠製作一個常規的「吐司」信息? –

回答

0

要獲得一個套接字連接到主機的地址,你應該使用getInetAddress()而非getLocalAddress()。因此,您的代碼可能如下所示:

public void onClick(View v) { 

    Socket s = new Socket(); 
    String host ="10.10.20.xxxx"; 

    try { 
     s.connect(new InetSocketAddress(host, 6000), 1000); 

     InetAddress inetAddress = s.getInetAddress();  // <---- Here! 
     String ip = inetAddress.getHostAddress(); 

     Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

現在試試這個解決方案,謝謝! – ulyssessPax

+0

我試過這段代碼,但是沒有消息出現 – ulyssessPax

+0

你可能會得到一個異常並且沒有看到它(因爲try ... catch)。嘗試向'catch'添加'Toast.makeText(getBaseContext(),「ERROR」,Toast.LENGTH_SHORT).show();'以幫助您調試。 –