3

I am using the following code to get the IP address of my android phone.

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();
                     //return inetAddress;
                 }
             }
         }
     } catch (SocketException ex) {
         Log.e("SALMAN", ex.toString());
     }

it returns fe80::94ae:97c:2680:c6cb%rmnet0

I then set up a server on port 8080.

How can I use this address to connect a client to it? I was expecting an IPv4 address... Can I connect to it via chrome or something to test the connection?

4

1 回答 1

2

Use either:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

Or:

try {
Socket socket = new Socket("www.stackoverflow.com", 80);
   Log.i("", socket.getLocalAddress().toString());
} catch (Exception e) {
   Log.i("", e.getMessage());
}

You can't test your connection via chrome but you can connect over it if you use the HTTP protocol. Write a Java SE desktop with another socket to communicate. The code is pretty similar.

于 2012-09-25T19:43:15.013 回答