简体   繁体   中英

Getting IP Address of another device (Sever) in Android

I am trying to build an android application that connects two or more devices as a client/server(using socket).

But problem is in client device user need to manually put IP address of Server device to connect with server. But from the client i don't know the server IP Address. and i don't want to enter it manually.

is there any way to get IP address(programmatically) of server device that using same application and on the same network ?

Any help would be greatly appreciated. Thank in advanced.

After trying many ways finally, I have got a solution which is

Network discovery using UDP broadcast (credit goes to this documentation )

(Thanks @Fildor for your suggestion to implement this service).

Solution

Using UDP packets and broadcasting them! This technique however is not optimal, but as long as we stay in one network this shouldn't be a problem. UDP packets however are fairly easy to work with.

Server implementation

  • Open a socket on the server that listens to the UDP requests.
  • Make a loop that handles the UDP requests and responses
  • Inside the loop, check the received UPD packet to see if it's valid
  • Still inside the loop, send a response to the IP and Port of the
    received packet

Client implementation

  • Open a socket on a random port.

  • Try to broadcast to the default broadcast address (255.255.255.255)

  • Loop over all the computer's network interfaces and get their broadcast addresses

  • Send the UDP packet inside the loop to the interface's broadcast address

  • Wait for a reply

  • When we have a reply, check to see if the package is valid

  • When it's valid, get the package's sender IP address; this is the server's IP address

  • CLOSE the socket! We don't want to leave open random ports on someone else's computer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM