Shine
Shine

Reputation: 3818

Android UDP inbound traffic

I'm trying to keep a listening UDP port on 23000, the app works well in local environment. But switching to 3G there are no chances, traffic is blocked.

I tried 'opening' the carrier channel sending 4bytes of data on the same port before receiving:

                InetAddress serverAddr = InetAddress.getByName(SOULISSIP);
                DatagramChannel channel = DatagramChannel.open();
                socket = channel.socket();

                //socket = new DatagramSocket();
                socket.setReuseAddress(true);

                //InetSocketAddress ia = new InetSocketAddress("localhost", SERVERPORT);
                InetSocketAddress sa = new InetSocketAddress(SERVERPORT);
                socket.bind(sa);
                DatagramPacket holepunh = new DatagramPacket(new byte[]{0,1,2,3},4, serverAddr, SERVERPORT);
                socket.send(holepunh);

                // create a buffer to copy packet contents into
                byte[] buf = new byte[200];
                // create a packet to receive


                DatagramPacket packet = new DatagramPacket(buf, buf.length);

                Log.d("UDP", "***Waiting on packet!");
                socket.setSoTimeout((int) opzioni.getDataServiceInterval());
                // wait to receive the packet
                socket.receive(packet);
                UDPSoulissDecoder.decodevNet(packet);
                socket.close();

is there a simple way to open the channel and receive UDP datagrams on port 23000?

Upvotes: 2

Views: 2136

Answers (1)

Shine
Shine

Reputation: 3818

So, the answer was in the request, while I was struggling with receiving socket. I had to bind the sender socket to the local port used for receiving datagrams:

            //send                
            serverAddr = InetAddress.getByName(SOULISSIP);

            DatagramChannel channel = DatagramChannel.open();
            sender = channel.socket();
            sender.setReuseAddress(true);

            //amateur hole punch
            InetSocketAddress sa = new InetSocketAddress(SERVERPORT);
            sender.bind(sa);
            //stuff to send
            List<Byte> macaco = new ArrayList<Byte>();
            macaco = Arrays.asList(pingpayload);
            ArrayList<Byte> buf = buildVNetFrame(macaco, prefs);
                    //someone help me here...
            byte[] merd = new byte[buf.size()];
            for (int i = 0; i < buf.size(); i++) {
                merd[i] = (byte) buf.get(i);
            }
            packet = new DatagramPacket(merd, merd.length, serverAddr, SOULISSPORT);
            sender.send(packet);

The receiver and the sender are on separate threads, using same local port. .setReuseAddress(true) permitted this.

Upvotes: 1

Related Questions