TCP connection between two android devices (even with NAT) - java

I am doing an android app allowing users to play online.
Currently, I use a TCP server: when two persons are connected, the server takes care of forwarding the packets between the two clients.
I would like to replace my server by a java servlet with google app engine. This new server will just be used to connect the two players.
It would work in that way:
Player A opens a server socket and then post to the server the connection details.
When a player B wants to play against A, he asks to the server the port number of A and he connects directly to A.
The problem is that I am not sure that it will work if player A is behind a NAT. When player A opens a server socket, that opens one port of its 192.168.x.y address, but does it ask to the box a port forwarding? I assume it doesn't...
So two questions:
Is it possible to make a direct connection TCP between two devices even when there is a NAT or a firewall (I don't know how firewalls work on Android...)
If it isn't possible, what is the best solution: Is it possible to make a TCP server to ensure the exchange of the messages with app engine?
Thank you by advance.
game

Creating direct TCP connection between users under different NAT is mostly possible. There are 4 types of NAT. FC, ARC, PRC, Symmetric. If one of player A or B has symmetric NAT then it is impossible to create TCP P2P connection. In this case you will have to use a server in the middle for exchanging data between two players.
For other types of NAT combinations it is very much possible but not guaranteed. The technique that is used to create TCP P2P connection is called TCP hole punching. Read this answer to know in details about this technique.
Also creating TCP P2P connection is not related to any platform.

First, the device itself is probably not going to be the main problem. If they are at home and using WiFi, you will probably have to deal with a cable modem/DSL modem, which typically includes a firewall. Also if they are at work (or a hotel, conference center, etc.), there may be a corporate firewall to deal with.
I believe most home cable/DSL modems support uPnP (Universal Plug and Play), which includes the Internet Gateway Device Protocol (IGD) designed to let devices determine the external IP address and set up port mappings. In general you can look up NAT traversal for ways to handle connections through a home modem/firewall. I will note that corporate firewalls are a different matter and many of these techniques won't work.
So probably I would recommend you be ready for at least the following four scenarios
Direct connection with nothing creating problems. You can test this by having the server do a test connection when the player first contacts the server. If this works, things are simple.
Home NAT device that understands uPnP. If you have a 10.x.x.x, 172.16.x.x-172.31.x.x, or 192.168.x.x number (typical home WiFi), then you can try to set up the NAT traversal and if that works you can send the appropriate information to your server. It probably would be worthwhile for the server to do a test connection just to be sure that things work.
If you have a firewall that you can't get around, then make a note on the server regarding player A, and when B tries to join A's game, look and see if B will accept connections, and if so then arrange for A to connect to B instead.
If none of the above work, then have A and B both connect to the server and have the server relay messages between A and B.
If you don't want to program all those possibilities, then option 4 is the one that is most likely to work, even if it does mean extra traffic going to/from your server. But note that for corporate networks, they may simply have a rule blocking unknown connections, and there may not be much you can do.
Edit: I was able to get a simple TCP server working on Android without anything special regarding Android itself, so removed a comment saying I didn't know about that.

Related

Java - communication through sockets

Let's say, within a program, there are capabilities to connect to a socket and server(which would be my own computer - localhost) and has all the handling for communicating to the server and back (receiving and sending messages like a chat service). If i send this program as a .jar file to two other users their respective machines, as the users executes the program, it would connect to this socket and server. If all was set up correctly (correctly writes and reads from the socket inputstream and outputstreams) and displays the messages on a GUI chat box, would the two users be able to communicate with this chat service?
Yes, but the main barrier that would prevent users from doing this is a little something called Network Address Translation (NAT).
In short, the vast majority of computers connected to the Internet do not have their own, unique, public IPv4 address (and the vast majority do not have IPv6 addresses either, because ISPs are dragging their feet in rolling out IPv6, but that's another matter entirely).
Dedicated servers often do have (usually multiple) unique IPv4 addresses, but significant numbers of IP addresses are usually only available to hosting companies that operate their own Autonomous System -- and even then, purchasing IPs these days is very expensive, because they're a valuable and rare commodity.
Anyway, two random users on some sort of home Internet connection (like cable, DSL, or fiber) almost certainly have a router or modem of some sort that performs NAT, giving each user device (computer, tablet, etc.) their own private LAN IP, instead of giving each device a unique public IP.
This means that inbound connections from the public Internet are, by default, ignored by the NAT gateway. So if you try to open a socket to your friend's public IP, unless that gateway (modem/router) has been configured correctly, it will just silently ignore your connection attempt, and you'll get a timeout or "connection refused" type message.
There are a few techniques for getting around this, but most of them either require much more complicated application network code, or require the user to mess around in their router configuration pages (which casual users usually aren't willing to do).
Port forwarding: Users must manually configure their router to "forward" public IP ports to a specific private IP, thus allowing the connection attempt on the public IP to pass through the Network Address Translation table to the private LAN. There is no general-purpose way of automating this without user intervention due to the differences between router/gateway devices.
NAT Traversal, which requires one of a variety of NAT-T protocols to be implemented in your program, and requires the explicit support of the desired NAT-T protocol for the routers involved (yours and your friend's). There are loads of different NAT-T protocols available; it'd be up to you to determine which one to use, based on compatibility, availability, etc.
Using an interposing server as an indirect way of routing packets between the two: In this case, you create a server on the public Internet that does have a unique IP (or has ports forwarded to it), and have each of your two client computers initiate an outbound connection to that server. The server would accept connections from both clients, then process the packets and pass them along, like talking to someone through a middleman. This doesn't require any special configuration on the clients, as long as they can make outbound connections on the desired ports (by default, most can, except in restricted enterprise environments where your ports may be limited to a few like 80 and 443.)
You'd need to adopt one of these techniques if your clients are using NAT. If one of your clients has a static IP directly connected to their computer and can accept incoming connections directly (without NAT), your program concept would work without modification, as long as the user behind the NAT initiates the connection to the one with a static IP.

UDP over Internet. How does it work?

As I am programming a network chat (java, but should not make a difference for the question), and wanted to use UDP, I ran into the problem of it not working over the internet. After a little research I found out that you have to have port forwarding for the specific port activated. So now it comes to my question:
Does UDP work over the Internet in a not configurable way?
For example, if I would program a whole Network Game would it make sense to use UDP? Or would I require the Player to activate Portforwarding and open the Port etc?
When would it make sense to use UDP then? And why?
I'm actually not understanding the whole point of UDP then.
For my programming point of view I would like to have a way to use it intuitive.
Like creating the DatagramSocket and the DatagramPacket, configure the Packet with the Data and the Destination and send it away over the internet.
As for my Users I don't want them to have to configure any specific things like opening the exact port they want to use etc. I just want them to use the program (server and client) and it should work.
The problem you've run into is not one of UDP vs TCP (although using the unreliable, unordered UDP as the basis of a chat application seems like an odd choice to me).
The problem is that of NAT traversal. In a nutshell, home routers perform a network function called NAT - Network Address Translation. They do it in order to use a single public IP address for all machines inside the NAT (which are given private addresses - usually 10.0.0.0 or 192.168.0.0). The router then switches the source IP address in all packets sent from inside the LAN from the private address to the public one. It uses port numbers to "remember" which machine sent what to what address, in order to perform the backwards translation when the response arrives.
The problem arises when someone wants to initiate a connection to a machine behind a NAT. Without seeing an outgoing connection first, the NAT doesn't know to which internal computer and port it should forward the packet. This is what happens to you.
There are various fixes for this issue, with the simplest one being manual port forwarding (as you've discovered), but it's a well known problem faced by any peer-to-peer application. If you need to contact a machine behind NAT (i.e. contact most home users) and you want your application to work out-of-the box (without your users fiddling with their routers) you need to research NAT traversal techniques, implement them in your application, and hope that the user's home routers support them. It's a huge pain in the neck.
EDITED: with Joachim Pileborg's correct suggestions!
UDP is often a better choice for action-based games, where it's vitally important to have updates to the client or server with the latest data about a player, player input, or the game world.
TCP begins with a 3-way handshake to establish a connection (which takes time). If your game communication protocol is via TCP, all packets in a message have to arrive before the message becomes available. Even a small amount of Internet congestion could cause your game to lag.
TCP is good for communications that MUST arrive in full.
With UDP, the client or server can send the latest player/game state in individual packets that do not depend on arriving in order. If a packet is late, or arrives out of order... it should be ignored.
UDP is good for communications that need to be fast, but losing individual packets is OK.
Both should be available in your Java platform.
Here's some further reading:
http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/

Peer 2 Peer connection in Java

I have been given a project in which I have to share files with peers without any intermediate server. I want to know how to know how many hosts are online on the network and how to connect to them. I have to roughly make Routing table for the hosts in my computer through Java.
You need not to keep any track of routing. All you need is to know the endpoints addresses.
You may find out if a host is connected to the network by establishing a connection with this host.
You mentioned that there will be no intermediate server, so the NAT hole punching is out of scope of your question.
As the starting point look at java.net.Socket class documentation.
I'm going to assume that this is on a private network. Something that's relatively contained. Letting them find each other over the internet sounds like a nightmare.
So, given this, one model for your peers to find each other might be to select a standardised sequence of ports and an alive signal. Then when a peer searches for others, it simply goes through all the IPs on the network and makes a request on that port number. If it gets an alive signal it adds it to a table. The signalled computer would have to record the new comer as well.
You'd have to select the port sequence such that they're generally unused on the network. (Quite large) I say sequence so that there's a preference in ordering to speed up the search.
To speed up the search even more, when an alive signal is sent, it could also send it's peers table and the IPs it checked (and the ones it received in the same way). Then the new peer would only have to check new IPs on the network since old IPs with a new instance of the program would establish themselves.
Hope that helps
i'd suggest you not to go with mac address,it will be better if you turn your dhcp off of your router (if you can include one of course........but if you only can include an hub you'll be forced i guess to use mac address).and use manual addressing for your ipv4 address,and you will be able to easily connect to the other computers.

Finding Open Port TCP Communication

I'm writing a Java application like AIM where I want a lookup server to help two clients connect to each other with the ServerSocket class. Unfortunately a serversocket needs an open port or it will be blocked by your firewall. Without having the clients manually change their firewall settings is there a way I can either find an open port, open a port (it's okay if it asks for permission) I just don't want every client to manually have to change firewall settings. Thanks!
Creating a ServerSocket is what opens the port on the server end (assuming the port is NOT also blocked on the firewall). On many systems, port numbers <1024 are not blocked by the firewall, and therefore often don't require custom configuration. However, since many ISPs have been more and more stringent with what ports they block within their network, many pieces of software have moved to operating over port 80. Why port 80? It's the port used for HTTP, and therefore pretty much open (at firewalls) 100% of the time for any service that operates on the web.
To answer the question of how to find an open port, port scanners perform this function. Basically all they do is try to establish a connection on a range of ports (say port 1-1024). When a connection is successful (in Java you would see this as a good connection over a Socket), you can consider that port "open". You don't need to exchange any data in order to make the connection, you just need to establish the connection, and then close it.
Also, if there is no server software of any kind running on the server, it won't appear "open", even if it isn't blocked. Without a successful Socket (TCP) connection, you won't know what ports are not blocked by user's firewall.
To reiterate, I'm switching back and forth between two related, but separate concepts. Firewalls can block/open ports, or have port forwarding. That's not the same as a port being "open" for connections on a given machine. In order for a machine to accept connections on a given port, there must be a piece of software listening for a connection on that port, otherwise no connection can be made.
I would suggest to look at a couple of alternative solutions that are less cumbersome - scanning for open ports can take quite some time, can cause panicky reactions from firewalls that feel attacked, and so on. There are a couple of techniques that are in active use and have been developed exactly to solve the problem of servers behind firewalls.
UDP Hole Punching, zero user side configuration needed. Simple explanation on how Skype uses this technique can be found here
UPnP / IGD could be used as an alternative, though less devices support it out of the box nowadays due to security problems.
STUN with a Java implementation of client and serverside called JSTUN
Whatever solution you choose, test it thoroughly with different internet service providers, there's a plethora of limitations you can expect wrt blocked ports.

How do I send data between two computers over the internet

I have been struggling with this for the entire day now, I hope somebody can help me with this.
My problem is fairly simple: I wish to transfer data (mostly simple commands) from one PC to another over the internet.
I have been able to achieve this using sockets in Java when both computers are connected to my home router. I then connected both computers to the internet using two different mobile phones and attempted to transmit the data again. I used the mobile phones as this provides a direct route to the internet and if I use my router I have to set up port forwarding, at least, that is how I understand it.
I think the problem lies in the method that I set up the client socket. I used:
Socket kkSocket = new Socket(ipAddress, 3333);
where ipAddress is the IP address of the computer running the server. I got the IP address by right-clicking on the connection, status, support. Is that the correct IP address to use or where can I obtain the address of the server? Also, is it possible to get a fixed name for my computer that I can use instead of entering the IP address, as this changes every time I connect to the internet using my mobile phone?
Alternatively, are there better methods to solving my problem such as using http, and if so, where can I find more information about this?
EDIT:
Would it be possible to have the server program running on a server on the internet somewhere. My original server would then be a client that send information to this server. This server would then pass this information to my original client and vice versa. That way, the IP address of my computer won't matter, as I only need to know the address of the server hosted somewhere on the web. Does this seem like a better solution? Where do I begin implementing such a solution?
Thanks!
When you connected to the server that serves StackOverflow, did you type in the IP address? It's 64.34.119.12, if that jogs your memory.
You probably didn't. You probably typed "stackoverflow.com". There's a huge, complex, clever, and in some ways, poorly implemented system called DNS that translates sensible and human-readable names into IP addresses.
One problem with DNS, though, is you need a "static IP", which is exactly what it sounds like: an IP address that doesn't change, which is exactly what you don't have.
So, what can you do?
You can buy a static IP account from your ISP (pretty expensive)
You can use some proxy out in the Internet (a machine that does have a static IP and is willing to bounce your packets back and forth -- I'm not aware of any service that does this for you; you could write one and put it up on Amazon Web Services or Google App Engine, both of which would be free at your level of usage, but they'd be slow, since every packet trying to cross your living room would have have to go via some data-center in Virginia).
You can keep doing what you're doing, looking in the net-configuration of your machine.
You could speed (3) up a little by having your server program look up its own IP address and print it out where you could see it and type it into the server by hand.
You can use DynDNS, as Sergey mentioned (this is the "right" solution, in that it's very general, it just might be a little complicated to set up)
You can use multi-casting.
Multi-casting is an interesting solution, and it may work for you. The idea is, when your server starts up, it announces to the net, "Here I am, I'm providing X server, here's my IP address, talk to me." The problem is, a multi-cast won't leave your living room. Obviously, if every multi-cast were spread to every computer on the Internet, the whole thing would collapse, so your router will ignore, and not route, multi-cast packets. That may or may not be a deal-breaker for you. EDIT Re-reading your question, I see it is a deal-breaker for you. I'd go with #5, but be aware there may be routing issues (address translations that prevent a server from knowing the address that other computers can find it at) or fire-wall issues (that is, your ISP may prevent your server from receiving incoming packets even if the address is correct).
using a direct socket connection with a port like 3333 is usually complicated because different network configurations.
firewalls will make a pleasure preventing the connection, or killing it from time to time.
maintaining a 2-way connection can be a nighmare. the SIP protocol is struggling with this kind of problems.
For a simple application, i suggest you look into the comet technology, where your clients can establish an http connection with a shared server. The server can then bridge commands between them.
html5 will also bring the websocket protocol to the table.
I got the IP address by right-clicking
on the connection, status, support.
Not sure about the "support" part, and I'm not on a Windows machine right now, but I think that the most easy and reliable way to figure out the IP address on Windows is to run "ipconfig" from the command line (Win+R, type "cmd", then "ipconfig" in the opened window). This, of course, should be done on the server side.
However, the problem is that depending on the ISP your IP address may be not within the Internet, but within a local ISP network (so-called NAT). In this case, you'll need to use some sort of black magic called TCP hole punching, which is very complicated and not guaranteed to work. You can figure out if your address is local or not by looking at it. For IPv4 local addresses are almost always like 10.x.x.x or 172.16-31.x.x, or 192.168.x.x. Don't know about IPv6.
You can also check your IP by visiting one of the special sites like www.whatismyip.com. If the address they tell you is different from the one you see by running "ipconfig" or looking at the connection properties, then you're almost certainly behind a NAT (or your ISP is using a transparent proxy, but that's rare).
If you are directly connected to Internet (no local addresses and NAT), then you should also check if you have any firewall software and either to configure it to allow connections to the port you use, or make sure it's in "ask the user" (and not "silently reject") mode, or just disable it completely (this may put your computer at risk, especially if there is no anti-virus software or the system isn't up-to-date).
Also, is it possible to get a fixed
name for my computer that I can use
instead of entering the IP address, as
this changes every time I connect to
the internet using my mobile phone?
Yes, it's possible. There is the thing called DynDNS, and there are DynDNS providers like DynDNS.com, where you can get a third-level domain name for free (like mycoolpc.dyndns.org). You'll have to install and configure some DynDNS client on your PC that will tell the DynDNS server its new IP each time each changed. I don't know anything about particular clients to use because I'm using the one built-in in my home router.
No need to write networking code for this, unless it really floats your boat. Take a look at SCP. http://amath.colorado.edu/computing/software/man/scp.html. There is a windows implementation where you can download putty (windows ssh client), and it is on most linux distributions. Alternatively, you could set up an FTP or SSH server on one or both of the machines.
"a fixed name for my computer that I can use instead of entering the IP address" would be a domain name, these are purchasable online for a few bucks.

Categories