I'm trying to create a Java program that can send a file from 1
Windows PC to another over a TCP/IP connection. As many people use
[wireless] routers, how can I create a TCP connection to PCs that are
connected to the internet via a router? The router has an IP and then
each PC connected to that has its own IP for their local network. How
would the router know which PC is the right one to send the data to?
The following assumes that by 'router' you mean a router that's acting
as a gateway to a private LAN.
If the router is working in transparent mode then all IPs on the inside
will be exposed to the world and anybody can connect to them unless
prevented by a firewall. However, this is not a typical case.
Usually the router will be working in NAT (Network Address Translation)
mode. By default the addresses used by hosts on the LAN are not exposed
to the outside world and, in fact, will typically be class C addresses
(192.168.x.y) which are intended to be used only on a private LAN that's
hidden from the world by the gateway router.
In this case there's no way that you can connect to a host on that LAN.
This is by design: a NAT-enabled router is also an effective firewall
against inward connections. Hosts on the LAN can still connect outward
unless the gateway router has been configured to prevent this. This
holds true regardless of whether the router's external IP address is
static or dynamic: if anybody knows the router's IP they can contact it
but it will refuse the connection.
There is one exception. The owner of the router can configure it to do
port forwarding. This means that the router can be configured to pass
inbound connection requests for that port to a specific host on the
inside LAN, i.e. if an internal host is running a web server the owner
might set his router to pass port 80 connections to the web host.
However, this can cause problems:
- unless the owner knows exactly what he is doing he can leave his
entire LAN open to attack via that port.
- forwarding a port to anything but a well secured, bulletproof
server is extremely foolish. IMHO forwarding it to a Windows
PC borders on having a death wish.
- many ISPs do not allow users to run servers, so port forwarding may
well break the owner's service contract with his ISP.