1
我在獲取設備的IP地址時遇到問題。無法獲取我設備的IP地址
我想將它用作服務器並將它連接到另一個將作爲客戶端的Android設備。
這是我爲服務器應用程序編寫的代碼。
public class ServerActivity extends Activity {
private TextView serverStatus;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
private EditText serverMessage;
String str="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverStatus = (TextView) findViewById(R.id.TextView01);
serverMessage = (EditText) findViewById(R.id.TextView02);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
str = line;
Log.d("ServerActivity", line);
handler.post(new Runnable() {
@Override
public void run() {
serverMessage.setText(str);
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
private String getLocalIpAddress()
{
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
return "ERROR Obtaining IP";
}
return "No IP Available";
}
@Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
當我開始我的應用程序,它顯示在文本視圖:
"Listening on IP: fe80::2254:76ff:fe85:f2bd%wlan0".
但是,我通過與其他IP地址的客戶端連接的是192.168.1.2(我在設備的設置中找到)。
我的問題是:如何在我的應用程序中獲得此第二個IP地址?
這個工作。謝謝!我接受了你的答案,但還不能投票。 – WWJD
好聽!乾杯! – NitZRobotKoder