How to get IP Address of Server (Socket) in Android?

笑着哭i 提交于 2020-02-25 07:39:05

问题


I'm creating a simple chat program that connects two android devices and they can send simple message I run the server with Socket on a port (1234 for example)

The problem is from the client i do not know the server IP Address. (and i dont want to enter it manually) is there a way to find a server that is running on a specific port?or can i run the server on some specific static IP that i can give it to clients?

if not is there another way to communicate with android devices that works on Android 2.2+(don't want to use wifi direct) ?

Thanks in Advance


回答1:


You can broadcast a udp message from the server specifying your ip in the message. Let the client receive the broadcast and use that msg as the ip address to connect to the socket. (PS : The broadcast receiver must b allowed to receive broadcasts). And you are done!




回答2:


Assign one SERVER predominantly for getting details such as IP ADDRESS, PORT number,etc.. from all the clients. Each client when activated will contact the SERVER to register itself first and will get the details(IP ADDRESS,etc) of other device to communicate. Now they can start waiting for specific device.




回答3:


On 4.1 you can use Mutlicast DNS for service discovery via the NsdManager (if you are on the same network). If you need this to work over the Internet/3G there is really no good way to do it. You could use Google Cloud Messaging (GCM) to notify clients about the server address, but in any case you will need one 'real' server on a stable address that all participants can reach.

http://developer.android.com/reference/android/net/nsd/NsdManager.html




回答4:


InetAddress.getLocalHost(); doesnot work for me but ya below code work for me

DhcpInfo dhcp = mWifiManager.getDhcpInfo();
int dhc = dhcp.serverAddress;

String dhcS = ( dhc & 0xFF)+ "."+((dhc >> 8 ) & 0xFF)+"."+((dhc >> 16 ) & 0xFF)+"."+((dhc >> 24 ) & 0xFF);

dhcS contains IP address of server,I used for Wireless connection between multiple devices.




回答5:


You can use this code

 connectionSocket.getRemoteSocketAddress();



回答6:


No the port can never be fixed with a IP. It is always provided by the user. To know the IP address of the server automatically, you can run this program associated with the chat program.

public class Net {
  public Net() throws UnknownHostException {
    InetAddress ia = InetAddress.getLocalHost();
    System.out.println(ia);
    ia = InetAddress.getByName("local host");
    System.out.println(ia);
  }

  public static void main(String args[]) throws UnknownHostException {
    Net a = new Net();
  }
}

You run can this program by the help of a button which is associated with your chat program.



来源:https://stackoverflow.com/questions/21604259/how-to-get-ip-address-of-server-socket-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!