I'm trying to to send a udp packet to a client across a NAT, both of us belong to a different NAT, we are familiar with the theory of STUN therefore the way to achieve this is to 'hole punch' our way through via a simple STUN server..
Basically the server just returns external IP address and port of another client that is 'connected' which I can then use it to send the packet to the client across the NAT... however though we managed to get each other's external ip and ports..we are still unable to receive anything from each other after sending... After searching through forums and many hours of head scratching we are still unable to come up with a solution...was wondering if anyone who is familiar with STUN to able to give us some pointers or advice on where we've gone wrong...
Below is our small client we've written...
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class Client {
DatagramSocket socket;
public Client(){
try {
socket = new DatagramSocket();
String data = "Initiate Stun Server";
byte[] receive = data.getBytes();
InetAddress host = InetAddress.getByName("the.stun.server.ipaddress");
DatagramPacket pk = new DatagramPacket(receive,receive.length,host,9345);
socket.send(pk); //send packet to server to initiate udp communication
//spawn a new Thread to listen for any incoming packets
new Thread(){
public void run(){
byte[] r;
DatagramPacket rp;
while(true){
System.out.println("Start listening on new socket");
r = new byte[1024];
rp = new DatagramPacket(r,r.length);
try {
socket.receive(rp);
System.out.println(new String(rp.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
String m = JOptionPane.showInputDialog(null,"Enter message to send");
InetAddress connect = InetAddress.getByName(JOptionPane.showInputDialog(null,"Enter address to send message to"));//This is where we input the external ip
int connectPort = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter port of the addressee"));//input port
DatagramPacket p = new DatagramPacket(m.getBytes(),m.getBytes().length,connect,connectPort);
socket.send(p);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
Client c = new Client();
}
}