简体   繁体   中英

With Java sockets, what is the correct address to connect to another device on a different network?

I want to use java Sockets to connect two Android devices on different networks. One device will act as a server and the other as a client. Which address will the server have to publish so that the client can connect to it?

java.net has the InetAddress class with the method getLocalHost() which provides an instance with localhost information (hostname, localhost address). If I run it on my machine, the address I'm given is 192.168.1.101. Is this the address the server device would have to publish in order for the client device to connect to it? I'm assuming no since it is a local address. Where, then, do I get the correct address of each device?

You can enumerate all network interfaces using NetworkInterface . You may also need to handle connectivity changes, such as switching from 3G to Wifi, etc. Generally, your device is not guaranteed to have a global IP address, so unless you only run it on your own network and you have a valid IP or have set up necessary NAT/port forwarding, etc. you may not able to connect to it.

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