How to get my IP address?

I have a serverSocket and I would like to know the IP address, but

listenSocket.getInetAddress().toString(); 

I get 0.0.0.0. How can I get the IP address or (if there are two connected connections) one of them?

+6
source share
3 answers

I have used this in the past:

 public 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(); } } } } catch (SocketException ex) { Log.e(LOG_TAG, ex.toString()); } return null; } 

Source: http://www.droidnova.com/get-the-ip-address-of-your-device,304.html

+14
source

Please check it. How to get device IP address from code? getting ipaddress is necessary after checking also InetAddressUtils.isIPv4Address (sAddr);

+2
source

If you get 0.0.0.0, this is probably because your listening socket accepts connections on all machine interfaces. As a rule, there will be at least two of them - one for communication with the outside world and the localhost / loopback interface. Therefore, it makes no sense to ask for one address.

Once you accept an incoming connection, you can give it the address of a specific interface that processes it.

A quick way to find a “good” IP address is to make an outgoing connection to a known site and request the address of its local end after it is connected. This is somewhat more portable than enumerating network interfaces (if you care about such things), but, of course, it requires that you have something that you can connect to the one you trust in order to be lively and achievable.

0
source

Source: https://habr.com/ru/post/895211/


All Articles