EzDevInfo.com

udp interview questions

Top udp frequently asked interview questions

UDP multicast group on Windows Phone 8

OK this is one I've been trying to figure out for a few days now. We have an application on Windows Phone 7 where phones join a multicast group and then send and receive messages to the group to talk to each other. Note - this is phone to phone communication.

Now I'm trying to port this application to Windows Phone 8 - using the 'Convert to Phone 8' feature in Visual Studio 2012 - so far so good. Until I try to test the phone to phone communication. The handsets seem to join the group fine, and they send the datagrams OK. They even receive the messages that they send to the group - however, no handset ever receives a message from another handset.

Here is the sample code behind to my page:

// Constructor
public MainPage()
{
    InitializeComponent();
}

// The address of the multicast group to join.
// Must be in the range from 224.0.0.0 to 239.255.255.255
private const string GROUP_ADDRESS = "224.0.1.1";

// The port over which to communicate to the multicast group
private const int GROUP_PORT = 55562;

// A client receiver for multicast traffic from any source
UdpAnySourceMulticastClient _client = null;

// Buffer for incoming data
private byte[] _receiveBuffer;

// Maximum size of a message in this communication
private const int MAX_MESSAGE_SIZE = 512;

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    _client = new UdpAnySourceMulticastClient(IPAddress.Parse(GROUP_ADDRESS), GROUP_PORT);
    _receiveBuffer = new byte[MAX_MESSAGE_SIZE];

    _client.BeginJoinGroup(
        result =>
        {
            _client.EndJoinGroup(result);
            _client.MulticastLoopback = true;
            Receive();
        }, null);
}

private void SendRequest(string s)
{
    if (string.IsNullOrWhiteSpace(s)) return;

    byte[] requestData = Encoding.UTF8.GetBytes(s);

    _client.BeginSendToGroup(requestData, 0, requestData.Length,
        result =>
        {
            _client.EndSendToGroup(result);
            Receive();
        }, null);
}

private void Receive()
{
    Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);
    _client.BeginReceiveFromGroup(_receiveBuffer, 0, _receiveBuffer.Length,
        result =>
        {
            IPEndPoint source;

            _client.EndReceiveFromGroup(result, out source);

            string dataReceived = Encoding.UTF8.GetString(_receiveBuffer, 0, _receiveBuffer.Length);

            string message = String.Format("[{0}]: {1}", source.Address.ToString(), dataReceived);
            Log(message, false);

            Receive();
        }, null);
}

private void Log(string message, bool isOutgoing)
{
    if (string.IsNullOrWhiteSpace(message.Trim('\0')))
    {
        return;
    }

    // Always make sure to do this on the UI thread.
    Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    {
        string direction = (isOutgoing) ? ">> " : "<< ";
        string timestamp = DateTime.Now.ToString("HH:mm:ss");
        message = timestamp + direction + message;
        lbLog.Items.Add(message);

        // Make sure that the item we added is visible to the user.
        lbLog.ScrollIntoView(message);
    });

}

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    // Don't send empty messages.
    if (!String.IsNullOrWhiteSpace(txtInput.Text))
    {
        //Send(txtInput.Text);
        SendRequest(txtInput.Text);
    }
}

private void btnStart_Click(object sender, RoutedEventArgs e)
{
    SendRequest("start now");
}

In order to simply test out the UDP stack, I downloaded the sample from MSDN found here and I tested this on a pair of Windows Phone 7 devices and it works as expected. Then I converted to Windows Phone 8 and deployed to my handsets, again the devices seem to initiate their connection, and the user can enter their name. However, again the devices can't see or communicate with other devices.

Finally I implemented a simple communication test using the new DatagramSocket implementation, and again I see successful initiation, but no inter-device communication.

This is the same code behind page using the datagram socket implementation:

// Constructor
public MainPage()
{
    InitializeComponent();
}

// The address of the multicast group to join.
// Must be in the range from 224.0.0.0 to 239.255.255.255
private const string GROUP_ADDRESS = "224.0.1.1";

// The port over which to communicate to the multicast group
private const int GROUP_PORT = 55562;

private DatagramSocket socket = null;

private void Log(string message, bool isOutgoing)
{
    if (string.IsNullOrWhiteSpace(message.Trim('\0')))
        return;

    // Always make sure to do this on the UI thread.
    Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    {
        string direction = (isOutgoing) ? ">> " : "<< ";
        string timestamp = DateTime.Now.ToString("HH:mm:ss");
        message = timestamp + direction + message;
        lbLog.Items.Add(message);

        // Make sure that the item we added is visible to the user.
        lbLog.ScrollIntoView(message);
    });
}

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    // Don't send empty messages.
    if (!String.IsNullOrWhiteSpace(txtInput.Text))
    {
        //Send(txtInput.Text);
        SendSocketRequest(txtInput.Text);
    }
}

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    socket = new DatagramSocket();
    socket.MessageReceived += socket_MessageReceived;

    try
    {
        // Connect to the server (in our case the listener we created in previous step).
        await socket.BindServiceNameAsync(GROUP_PORT.ToString());
        socket.JoinMulticastGroup(new Windows.Networking.HostName(GROUP_ADDRESS));
        System.Diagnostics.Debug.WriteLine(socket.ToString());
    }
    catch (Exception exception)
    {
        throw;
    }
}

private async void SendSocketRequest(string message)
{
    // Create a DataWriter if we did not create one yet. Otherwise use one that is already cached.
    //DataWriter writer;
    var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(GROUP_ADDRESS), GROUP_PORT.ToString());
    //writer = new DataWriter(socket.OutputStream);
    DataWriter writer = new DataWriter(stream);

    // Write first the length of the string as UINT32 value followed up by the string. Writing data to the writer will just store data in memory.
   // stream.WriteAsync(
    writer.WriteString(message);

    // Write the locally buffered data to the network.
    try
    {
        await writer.StoreAsync();
        Log(message, true);
        System.Diagnostics.Debug.WriteLine(socket.ToString());
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        writer.Dispose();
    }
}

void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
    try
    {
        uint stringLength = args.GetDataReader().UnconsumedBufferLength;
        string msg = args.GetDataReader().ReadString(stringLength);

        Log(msg, false);
    }
    catch (Exception exception)
    {
        throw;
    }
}

Last night I took the handsets home to test them on my home wireless network, low and behold I get successful device communication.

So to recap - my legacy Windows Phone 7 code runs fine on my work network. The port to Windows Phone 8 (no actual code change) does not send inter-device communication. This code does work on my home network. The code runs with the debugger attached and there are no signs of errors or exceptions anywhere during execution.

The handsets I'm using are:

Windows Phone 7 - Nokia Lumia 900 (* 2), Nokia Lumia 800 (* 3) Windows Phone 8 - Nokia Lumia 920 (* 1), Nokia Limia 820 (* 2)

These are all running the latest OS, and are in developer mode. Development environment is Windows 8 Enterprise running Visual Studio 2012 Professional

I cant tell you much about the work wireless network - other than the Phone 7 devices have no trouble.

As for the home wireless network i used, that's just a basic BT Broadband router with none of the 'out the box' settings altered.

Clearly there is an issue with the way that the two network are configured, but there is also very clearly an issue with the way Windows Phone 8 implements UDP messages.

Any input would be appreciated as this is driving me mad right now.


Source: (StackOverflow)

How to find the largest UDP packet I can send without fragmenting?

I need to know what the largest UDP packet I can send to another computer is without fragmentation.

This size is commonly known as the MTU (Maximum Transmission Unit). Supposedly, between 2 computers, will be many routers and modems that may have different MTUs.

I read that the TCP implementation in windows automatically finds the maximum MTU in a path.

I was also experimenting, and I found out that the maximum MTU from my computer to a server was 57712 bytes+header. Anything above that was discarded. My computer is on a LAN, isn't the MTU supposed to be around 1500 bytes?


Source: (StackOverflow)

Advertisements

Can TCP and UDP sockets use the same port?

First of all, is there any problem with using both UDP and TCP on the same server?

Secondly, can I use the same port number?


Source: (StackOverflow)

When is it appropriate to use UDP instead of TCP?

Since TCP guarantees packet delivery and thus can be considered "reliable", whereas UDP doesn't guarantee anything and packets can be lost. What would be the advantage of transmitting data using UDP in an application rather than over a TCP stream? In what kind of situations would UDP be the better choice, and why?

I'm assuming that UDP is faster since it doesn't have the overhead of creating and maintaining a stream, but wouldn't that be irrelevant if some data never reaches its destination?


Source: (StackOverflow)

Can two applications listen to the same port?

As simple as it gets - can two applications on the same machine bind to the same port and ip address? Taking it a step further, can one app listen to requests coming from a certain ip and the other to another remote ip? I know I can have one application that starts off two threads (or forks) to have similar behavior, but can two applications that have nothing in common do the same?

thanks.


Source: (StackOverflow)

How is TeamViewer so fast?

Sorry about the length, it's kinda necessary.

Introduction

I'm developing a remote desktop software (just for fun) in C# 4.0 for Windows Vista/7. I've gotten through basic obstacles: I have a robust UDP messaging system, relatively clean program design, I've got a mirror driver (the free DFMirage mirror driver from DemoForge) up and running, and I've implemented NAT traversal for all NAT types except Symmetric NATs (present in corporate firewall situations).

Regarding screen transfer/sharing, thanks to the mirror driver, I'm automatically notified of changed screen regions and I can simply marshal the mirror driver's ever-changing screen bitmap to my own bitmap. Then I compress the screen region as a PNG and send it off from the server to my client. Things are looking pretty good, but it's not fast enough. It's just as slow as VNC (btw, I don't use the VNC protocol, just a custom amateur protocol).

From the slowest remote desktop software to the fastest, the list usually begins at all VNC-like implementations, then climbs up to Microsoft Windows Remote Desktop...and then...TeamViewer. Not quite sure about CrossLoop, LogMeIn - I haven't used them, but TeamViewer is insanely fast. It's quite literally live. I ran a tree command on Command Prompt and it updated with 20 ms delay. I can browse the web just a few milliseconds slower than on my laptop. Scrolling code vertically in Visual Studio has 50 ms lag time. Think about how robust TeamViewer's screen-transfer solution must be to accomplish all this.

VNCs use poll-based hooks for detecting screen change and brute force screen capturing/comparing at their worst. At their best, they use a mirror driver like DFMirage. I'm at this level. And they use something called the RFB protocol.

Microsoft Windows Remote Desktop apparently goes one step higher than VNC. I heard, from somewhere on StackOverflow, that Windows Remote Desktop doesn't send screen bitmaps, but actual drawing commands. That's quite brilliant, because it can just send simple text (draw this rectangle at this coordinate and color it with this gradient)! Remote Desktop really is pretty fast - and it's the standard way of working from home. And it uses something called the RDP protocol.

Now TeamViewer is a complete mystery to me. Apparently, they released their source code for Version 2 (TeamViewer is Version 7 as of February 2012). People have read it and said that Version 2 is useless - that it's just a few improvements over VNC with automatic NAT traversal.

But Version 7...it's ridiculously fast now. I mean, it's actually faster than Windows Remote Desktop. I've streamed DirectX 3D games with TeamViewer (at 1 fps, but Windows Remote Desktop doesn't even allow DirectX to run).

By the way, TeamViewer does all this without a mirror driver. There is an option to install one, and it gets just a bit faster.

The Question

My question is, how is TeamViewer so fast? It must not be possible. If you've got 1920 by 1080 resolution at even 24 bit depth (16 bit depth would be noticeably ugly), thats still 6,220,800 bytes raw. Even using libjpeg-turbo (one of the fastest JPG compression libraries used by large corporations), compressing it down to 30KB (let's be extremely generous), would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers). And that libjpeg-turbo compression would take time to compress. High-quality JPG compression takes 175 milliseconds for a full 1920 by 1080 screenshot for me. And that number goes up if the host's computer runs an Atom processor. I simply don't understand how TeamViewer has optimized their screen transfer so well. Again, small-size images might be highly compressed, but take at least tens of milliseconds to compress. Large-size images take no time to compress, but take a long time to get through. Somehow, TeamViewer completes this entire process to get roughly 20-25 frames per second. I've used a network monitor, and TeamViewer is still lagless at speeds of 500 Kbps and 1 Mbps (VNC software lag for a few seconds at that transfer rate). During my tree Command Prompt test, TeamViewer was receiving inbound data at a rate of 1 Mbps and still running 5-6 fps. VNC and remote desktop don't do that. So, how?

The answers will be somewhat complicated and intricate, so please don't post your $0.02 if you're only going to say it's because they use UDP instead of TCP (would you believe they actually do use TCP just as successfully though).

I'm hoping there's a TeamViewer developer somewhere here on StackOverflow.

Potential Answers

Will update this once people reply.

  1. My thoughts are, first of all, that TeamViewer has very fine network control. For example, they split large packets to just under the MTU size and never waste a trip. They probably have all sorts of fancy hooks to detect screen changes along with extremely fast XOR image comparisons.

Source: (StackOverflow)

Difference between TCP and UDP? [closed]

What is the difference between TCP and UDP?

I know that TCP is used in the case of non-time critical applications, and UDP is used for games or applications that require fast transmission of data. I know that TCP is used for HTTP, HTTPs, FTP, SMTP, and Telnet. I know that UDP is used for DNS and DHCP.

But why? What characteristics of TCP and UDP make it useful for their respective use cases?


Source: (StackOverflow)

Does HTTP use UDP

This might be a silly question:

Does HTTP ever use the User Datagram Protocol? For example if one is streaming a MP3 or a video over the web using HTTP does it internally use UDP for the transport?


Source: (StackOverflow)

Why Does RTP use UDP instead of TCP?

I wanted to know why UDP is used in RTP rather than TCP ?. Major VoIP Tools used only UDP as i hacked some of the VoIP OSS.


Source: (StackOverflow)

UDP hole punching not going through on 3G

I'm trying to implement in a software a hole punching feature. The thing is, I'm implementing this with an already made TCP Server to communicate with Users.

Here's what I have so far :

  • "A" sends a message to an UDP Server "US" (on port 9333)
  • "US" sends back to "A" the port it has connected to (port 31000 - localport 31005)
  • "A" sends a message to a TCP Server "TS" saying he want's to connect to B (and give the port 31000)
  • "TS" sends a message to "B" giving him the "A"'s port (31000) and ip
  • "B" sends a message to "US" (on port 9333)
  • "US" sends a message to "B" telling him his port 45000 (localport 45005)
  • "B" sends a message to "TS" giving is udp port (45000)
  • "TS" sends a message to "A" giving B's udp port (45000) and ip
  • "A" start sending udp message to B's ip on port 45000 and listen on localport 31005
  • "B" start sending udp message to A's ip on port 31000 and listen on localport 45005

Of course ports 31000, 31005, 45000 and 45005 are here for example, every new connection the port change, only 9333 is static.

I know there is a lot of back-and-forth, more than it should really be. The fact is I'm bound to use the TCP server to communicate with both users, the udp server is just here to return User's port to himself so it can send it back to TCP Server.

However messages between users are not received by any... Anyone would have an idea why ?


EDIT :

I have tested my router with http://nattest.net.in.tum.de/test.php and udp hole punching works fine, so the issue is not coming from my router, but from my protocol...

When users are behind the same NAT, everything works fine, of course it uses privates ip, but it means that the code is working also, so every though leads to a protocol issue...


EDIT 2 :

Actually, I made it half work (And the problem was coming from my code actually, not the protocol... I have connected 2 users, one in 3G with an iPhone, one behind my NAT on Wifi.

The funny (well not so much) thing is, only one socket were able to receive and send data between both users. (the socket initiated by the iphone) According to the protocol I should have 2 well-connected sockets, am I wrong ?

So I managed to punch a hole in my NAT, but actually not in the cellular NAT.

Of course, I tested right away 2 iphones connected in 3G. And no one get's the message from the other.

Did I missed something about cellular NAT ?

P.S. : Sorry for updating so much my question, but since I get no answer I'm trying to find by myself...

P.S. 2 : Since I managed to punch a hole in my NAT, I have changed the title adding "on 3G"


EDIT 3 : I ran the http://nattest.net.in.tum.de/test.php test again with my computer connected to internet through my iphone's 3G connection.

Here's the result : UDP HOLE PUNCHING RESULT

Apparently all udp hole punching test were successful on the 9th test.

Further more it seems :

UDP Binding Test (?): Endpoint independent binding, port prediction is easy

So it should not be any trouble connecting 2 peers over 3G Connection (well not much than behind a "home" NAT)... Am I right ?


EDIT 4 :

Just to be sure, I now send a message to two distinct UDP Server, to check if the port and the local port are the same on 3G.

Long story short, ports (local and public) are the same when connecting on both server. so the test done on EDIT 2 was right, udp is endpoint independent, so there should not be any issue doing the hole punching I guess... (At least with my ISP)


Source: (StackOverflow)

Best C++ RTP/RTSP library [closed]

I'm looking for a RTP/RTSP library in C++. I found pjsip but it is more C-style. I'm looking for more OO library.


Source: (StackOverflow)

A firewall for Android with VpnService. Responses are delivered, but a SocketTimeoutException is thrown

I am implementing a simple firewall for Android using VpnService. My app is similar to ToyVpnService, but it doesn't send raw IP packets to a remote VPN server which would forward them to their destinations.

My implementation is here: https://bitbucket.org/MaksimDmitriev/norootfirewall/src/006f7c33cd1cd4055f372ed3a88664fe2a4be3dd/src/com/norootfw/NoRootFwService.java?at=unix

Can I do all this forwarding routine locally? That's what I'm trying to implement.

I initialize a TUN device and its file descriptors:

mInterface = new Builder().setSession(getString(R.string.app_name))
                .addAddress("10.0.2.1", 24)
                .addRoute("0.0.0.0", 1)
                .addRoute("128.0.0.0", 1)
                .establish();

in = new FileInputStream(mInterface.getFileDescriptor());
out = new FileOutputStream(mInterface.getFileDescriptor());

I assign 0.0.0.0/1 and 128.0.0.0/1 to the TUN device to make it more preferable than the default route with 0.0.0.0/0. I used 0.0.0.0/0 and ran into the same exception which is below.

And here is a sample UDP request.

1). I read an IP packet from the TUN device.

05-06 00:46:52.749: D/UDPChecksum(31077): Sent == [69, 0, 0, 36, 0, 0, 64, 0, 64, 17, 108, 91, 10, 0, 2, 1, -64, -88, 1, -59, -53, 1, -50, -87, 0, 16, 89, -114, 85, 68, 80, 95, 68, 65, 84, 65]

Please consider the IPv4 packet structure here. For example, the first number 69 (0100 0101 in binary) means that the version of the IP protocol is 4 (4 high-order bits). And the 4 low-order bits stand for the Internet Header Length (IHL) in 32-bit words.

2). Then a create a protected DatagramSocket and send the data (without its IP and UDP headers) to the destination address I'd read from the captured IP packet.

3). I receive a response from the remote machine and want to send it back to the app which initialized the request.

4). I swap the source and destination IP addresses and port numbers in the IP packet, calculate the IPv4 header checksum and the UDP checksum (having constructed an IPv4 pseudo header).

05-06 00:46:52.889: D/UDPChecksum(31077): mIpv4PseudoHeader == [-64, -88, 1, -59, 10, 0, 2, 1, 0, 17, 0, 14]

5). Afterwards I set the calculated checksums to the corresponding indexes of the IP packet and write the IP packet to out, the output stream of the TUN device.

05-06 00:46:52.889: D/UDPChecksum(31077): To TUN == [69, 0, 0, 34, 0, 0, 64, 0, 64, 17, 108, 93, -64, -88, 1, -59, 10, 0, 2, 1, -50, -87, -53, 1, 0, 14, -105, -72, 85, 68, 80, 95, 79, 75]

The response reaches my app. The DatagramSocket which has been blocked after calling its receive() method fills the buffer I provide.

        byte[] responseBuffer = new byte[RESPONSE_SIZE];
        try {
            mDatagramSocket.send(mDatagramPacket);
            final DatagramPacket response = new DatagramPacket(responseBuffer, responseBuffer.length);
            mDatagramSocket.receive(response);
        } catch (IOException e) {
            Log.e("NoRootFwService", "error: " + Arrays.toString(responseBuffer)); // I can see the correct response here.
            logException(e);
        }

But its socket throws an exception when the timeout is exceeded.

05-05 23:46:58.389: E/CLIENT(20553): java.net.SocketTimeoutException
05-05 23:46:58.389: E/CLIENT(20553):    at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:551)
05-05 23:46:58.389: E/CLIENT(20553):    at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
05-05 23:46:58.389: E/CLIENT(20553):    at java.net.PlainDatagramSocketImpl.doRecv(PlainDatagramSocketImpl.java:161)
05-05 23:46:58.389: E/CLIENT(20553):    at java.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:169)
05-05 23:46:58.389: E/CLIENT(20553):    at java.net.DatagramSocket.receive(DatagramSocket.java:250)
05-05 23:46:58.389: E/CLIENT(20553):    at socket.client.MainActivity$UdpThread.run(MainActivity.java:195)
05-05 23:46:58.389: E/CLIENT(20553): Caused by: libcore.io.ErrnoException: recvfrom failed: EAGAIN (Try again)
05-05 23:46:58.389: E/CLIENT(20553):    at libcore.io.Posix.recvfromBytes(Native Method)
05-05 23:46:58.389: E/CLIENT(20553):    at libcore.io.Posix.recvfrom(Posix.java:141)
05-05 23:46:58.389: E/CLIENT(20553):    at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
05-05 23:46:58.389: E/CLIENT(20553):    at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
05-05 23:46:58.389: E/CLIENT(20553):    ... 4 more

Everything works properly without the firewall. I read these discussions, but they weren't helpful:


Source: (StackOverflow)

JavaScript WebSockets with UDP?

I'm writing a JavaScript Application that has to receive a huge amount of data from other users. It is not important if some of this data gets lost. Is there some way of using JavaScript WebSockets with UDP instead of TCP?


Source: (StackOverflow)

UDP vs TCP, how much faster is it?

For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP?


Source: (StackOverflow)

What is the largest Safe UDP Packet Size on the Internet

I've read a number of articles about UDP packet sizes but have been unable to come to a conclusion on whats correct.

A number of services restrict the largest UDP packet to 512 bytes (like dns)

Given the minimum MTU on the internet is 576 , and the size of the IPv4 header is 20 bytes, and the UDP header 8 bytes. This leaves 548 bytes available for user data

Would I be able to use packets up to the size of 548 without packet fragmentation? Or is there something the creators of DNS knew about, and that why they restricted it to 512 bytes.

Could I even go higher than 548 bytes safely?


Source: (StackOverflow)