开发者

Java Socket on Different Machine Does Not Work

I've tried many examples on web and one of them is this: http://zerioh.tripod.com/ressources/sockets.html

All of the server-client socket examples work fine when they are tested with 127.0.0.1

BUT it never ever EVAR works on two different computers with actual raw real IP address ("could not connect to host" on telnet and "connection timed out" when tested on java client - the server program just waits for connection)

Note:

  • Firewall is turned off for sure
  • IP address from ipconfig didn't work
  • IP address from myipaddress.com (w开发者_如何学Chich is totally different for no reason than that from ipconfig) didn't work

What is it that I'm missing? If I can only figure this out...


Try binding on 0.0.0.0. This tells your socket to accept connections on every IP your local can accept upon.


Based on the comment where the the following snippet of code is mentioned:

requestSocket = new Socket("10.0.0.5", 2004); // ip from ipconfig 

it would be better to use the hostname instead of the IP address in the constructor, as the two-parameter Socket constructor with a String argument expects the hostname as the String, and not an IP address. A lookup of the IP address is then performed on the provided hostname.

If you need to pass in an IP address, use the two-parameter constructor that accepts the InetAddress as an argument. You can then provide a raw IP address to the InetAddress.getByAddress method, as shown in the following snippet:

InetAddress addr = InetAddress.getByAddress(new byte[]{10,0,0,5});

You'll need to be careful when specifying arguments via the byte array, as bytes are signed in Java (-127 through +128), and numbers beyond this range (but valid octets of IP addresses) may have to be specified using Integer.byteValue.

Finally, it should be noted that it is important to specify the IP address of the remote machine, as visible to the client. The IP address listed at myipaddress.com may be the address of a proxy, as that is the public IP of your entire network as visible to the host server at myipaddress.com. Therefore, you ought to be specify the IP address of the remote machine that is visible to your machine and not myipaddress.com.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜