Are there any disadvantgaes of using a part of the datagram in UDP to receive packets sequentially? - networking

The UDP protocol does not guarantee packets being received sequentially, but you could just use part of the datagram for a sequence number.
Compared to the guarantee of TCP, is the above solution for UDP equivalent?
Basically, I've been reading everywhere that UDP does not provide sequential receiving, but this seems like such an obvious fix that I was wondering if it is truly an adequate fix.

The only 'disadvantage' is that you lose a few bytes of data space.
However, by itself, it isn't a solution. You have to add ACK messages into your protocol so that the sender knows what you have and haven't received; you have to buffer sent datagrams at the sender until they are ACK'd in case you have to retransmit then; and you have to either buffer out of sequence datagrams or throw them away so you can reconstruct the sequence correctly. Having come this far, it would also be sensible for the sender to implement some form of flow control or pacing if it notices a lot of retransmission being required.
This is a good way towards implementing TCP. Most people give up at this point and use TCP.

Using UDP in that fashion makes the application need to handle packet reconstruction and sequencing. That creates overhead in the application layer of the network. TCP is probably more efficient at handling that in the transport layer.
As well, UDP does not provide a mechanism for resending lost packets. When your application notices that the sequence numbers skipped one, there is some ambiguity in the meaning. Is there a lost packet or a delay packet? Your application would need to be able to detect that, and be able to request that the packet be sent again via a packet number reference.
In other words, there is a reason for the overhead of TCP when in-order guaranteed delivery is required.
https://en.wikipedia.org/wiki/User_Datagram_Protocol

It sounds like you want a form of partial reliability, inbetween TCP and UDP.
An option is to use SCTP-over-UDP (SCTP, portable userspace & kernel source). SCTP lets you set in-order for unreliable UDP-like streams , and also for partially-reliable streams (limited time or number of re-transmits)
.

Of course you could implement the missing features from TCP in UDP but that would destroy the purpose of UDP. The point is that the TCP implementation in your network stack peforms all the neccessary operations for you. (Involving packet reassembling and packet loss).
If you need TCP than you should use it. UDP is designed for packets where you don't care if they got lost (like VOIP, Gameserver, etc.).

Related

Advantages of UDP over TCP?

TCP has a greater computation overhead to ensure reliable delivery of packets. But, since modern networks are fast, is there any scenario in which performance of UDP outweighs the reliability of TCP?
Is there any other particular advantage of UDP over TCP?
I can see two cases, where UDP would have an upper hand over TCP.
First, one of the attractive features of UDP is that since it does not need to retransmit lost packets nor does it do any connection setup, sending data incurs less delay. This lower delay makes UDP an appealing choice for delay-sensitive applications like audio and video.
Second, multicast applications are built on top of UDP since they have to do point to multipoint. Using TCP for multicast applications would be hard since now the sender would have to keep track of retransmissions/sending rate for multiple receivers.
It depends on your usage. If your application is time sensitive, like Voice over IP, then you don't care about missing packets. What you care about is the delay in that case.
You should have a look at this answer: What are examples of TCP and UDP in real life?
You could also look at the Wikipedia related section: http://en.wikipedia.org/wiki/User_Datagram_Protocol#Comparison_of_UDP_and_TCP
Applications that require constant data flow, bulk data and which require fastness than reliability uses UDP over TCP.
udp provides better application level control over what data is sent....since the data is packaged in a udp segment and immediately passed over to the network layer......hence no-frills segment delivery service is observed.
There is no need for connection establishment hence no delay(unlike tcp...which requires handshaking before the actual data transfer)
There is no need to maintain connection state in the end systems(ie no need for send and receive buffers,congestion control parameters and sequence and acknowledgement number parameters)..hence more active clients could be supported
Small packet header overhead for udp(only 8 bytes) where as tcp has 20 bytes of header
Facebook uses UDP connections instead of TCP/IP to connect to theirs Memcached Servers
There are couple of differences of UDP over TCP.
First, TCP is connection-based whereas UDP is connectionless.
Connection-based: Make sure that all messages will arrive and arrive in the correct order.
Connectionless: It does not guarantee order or completeness.
Second, Here is why UDP is faster over TCP:
UDP does not require ACK message back
UDP has no flow control
No duplication verification at the receiving end
Shorter header

I'm confused on terminology about wifi

I am trying to simulate a wifi video transmission and for that I created a connection using a socket between 2 devices, however I then started to doubt whether this is required or if I was supposed to create a UDP connection.
I think I'm just confused on terms here and I've Googled and I found out that Wifi can has TCP or UDP my question would then be would a Wifi Transmission over TCP be as reliable for a simulation as one with UDP?
I'd suggest you to read Difference between TCP and UDP?.
For streaming like video transmission you would generally want to use UDP. If a packet cannot reach the server in time, it'd better be discarded than pausing the whole transmission in order to wait for one tiny missing packet that just contains the other person blinking.
But obviously it's up to you and how you implement your software.
You may need to read up a bit on the TCP/IP protocol. TCP and UDP are just types of packets/datagrams. The main difference is that TCP packets include extra protocol information, whereas UDP are simpler packets with just a destination, the data itself, and a checksum.
The upshot is that the sender of a UDP packet has no way of knowing whether or not the packet was received at the other end. Often this doesn't matter - because it may be handled in other ways by higher layers in the software, or can be simply lost and ignored without any negative consequences. So UDP can be a more efficient use of the bandwidth, in some scenarios - because there is less protocol information being exchanged, and therefore more actual data. Plus TCP is more complicated because you have to handle the protocol stuff.
So when you create your system, you have a choice - either TCP or UDP packets, depending on what you are trying to achieve and how you want to go about it. But both packet types are really all part of the "tcp/ip" protocol stack, and have similarities.

Difference between TCP and UDP?

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?
TCP is a connection oriented stream over an IP network. It guarantees that all sent packets will reach the destination in the correct order. This imply the use of acknowledgement packets sent back to the sender, and automatic retransmission, causing additional delays and a general less efficient transmission than UDP.
UDP is a connection-less protocol. Communication is datagram oriented. The integrity is guaranteed only on the single datagram. Datagrams reach destination and can arrive out of order or don't arrive at all. It is more efficient than TCP because it uses non ACK. It's generally used for real time communication, where a little percentage of packet loss rate is preferable to the overhead of a TCP connection.
In certain situations UDP is used because it allows broadcast packet transmission. This is sometimes fundamental in cases like DHCP protocol, because the client machine hasn't still received an IP address (this is the DHCP negotiaton protocol purpose) and there won't be any way to establish a TCP stream without the IP address itself.
From the Skullbox article:
TCP (Transmission Control Protocol) is the most commonly used protocol on the Internet.
The reason for this is because TCP offers error correction. When the TCP protocol is used there is a "guaranteed delivery." This is due largely in part to a method called "flow control." Flow control determines when data needs to be re-sent, and stops the flow of data until previous packets are successfully transferred. This works because if a packet of data is sent, a collision may occur. When this happens, the client re-requests the packet from the server until the whole packet is complete and is identical to its original.
UDP (User Datagram Protocol) is anther commonly used protocol on the Internet. However, UDP is never used to send important data such as webpages, database information, etc; UDP is commonly used for streaming audio and video. Streaming media such as Windows Media audio files (.WMA) , Real Player (.RM), and others use UDP because it offers speed! The reason UDP is faster than TCP is because there is no form of flow control or error correction. The data sent over the Internet is affected by collisions, and errors will be present. Remember that UDP is only concerned with speed. This is the main reason why streaming media is not high quality.
1) TCP is connection oriented and reliable where as UDP is connection less and unreliable.
2) TCP needs more processing at network interface level where as in UDP it’s not.
3) TCP uses, 3 way handshake, congestion control, flow control and other mechanism to make sure the reliable transmission.
4) UDP is mostly used in cases where the packet delay is more serious than packet loss.
Think of TCP as a dedicated scheduled UPS/FedEx pickup/dropoff of packages between two locations, while UDP is the equivalent of throwing a postcard in a mailbox.
UPS/FedEx will do their damndest to make sure that the package you mail off gets there, and get it there on time. With the post card, you're lucky if it arrives at all, and it may arrive out of order or late (how many times have you gotten a postcard from someone AFTER they've gotten home from the vacation?)
TCP is as close to a guaranteed delivery protocol as you can get, while UDP is just "best effort".
Reasons UDP is used for DNS and DHCP:
DNS - TCP requires more resources from the server (which listens for connections) than it does from the client. In particular, when the TCP connection is closed, the server is required to remember the connection's details (holding them in memory) for two minutes, during a state known as TIME_WAIT_2. This is a feature which defends against erroneously repeated packets from a preceding connection being interpreted as part of a current connection. Maintaining TIME_WAIT_2 uses up kernel memory on the server. DNS requests are small and arrive frequently from many different clients. This usage pattern exacerbates the load on the server compared with the clients. It was believed that using UDP, which has no connections and no state to maintain on either client or server, would ameliorate this problem.
DHCP - DHCP is an extension of BOOTP. BOOTP is a protocol which client computers use to get configuration information from a server, while the client is booting. In order to locate the server, a broadcast is sent asking for BOOTP (or DHCP) servers. Broadcasts can only be sent via a connectionless protocol, such as UDP. Therefore, BOOTP required at least one UDP packet, for the server-locating broadcast. Furthermore, because BOOTP is running while the client... boots, and this is a time period when the client may not have its entire TCP/IP stack loaded and running, UDP may be the only protocol the client is ready to handle at that time. Finally, some DHCP/BOOTP clients have only UDP on board. For example, some IP thermostats only implement UDP. The reason is that they are built with such tiny processors and little memory that the are unable to perform TCP -- yet they still need to get an IP address when they boot.
As others have mentioned, UDP is also useful for streaming media, especially audio. Conversations sound better under network lag if you simply drop the delayed packets. You can do that with UDP, but with TCP all you get during lag is a pause, followed by audio that will always be delayed by as much as it has already paused. For two-way phone-style conversations, this is unacceptable.
One of the differences is in short
UDP : Send message and dont look back if it reached destination, Connectionless protocol
TCP : Send message and guarantee to reach destination, Connection-oriented protocol
TCP establishes a connection before the actual data transmission takes place, UDP does not. In this way, UDP can provide faster delivery. Applications like DNS, time server access, therefore, use UDP.
Unlike UDP, TCP uses congestion control. It responses to the network load. Unlike UDP, it slows down when network congestion is imminent. So, applications like multimedia preferring constant throughput might go for UDP.
Besides, UDP is unreliable, it doesn't react on packet losses. So loss sensitive applications like multimedia transmission prefer UDP. However, TCP is a reliable protocol, so, applications that require reliability such as web transfer, email, file download prefer TCP.
Besides, in today's internet UDP is not as welcoming as TCP due to middle boxes. Some applications like skype fall down to TCP when UDP connection is assumed to be blocked.
Run into this thread and let me try to express it in this way.
TCP
3-way handshake
Bob: Hey Amy, I'd like to tell you a secret
Amy: OK, go ahead, I'm ready
Bob: OK
Communication
Bob: 'I', this is the first letter
Amy: First letter received, please send me the second letter
Bob: ' ', this is the second letter
Amy: Second letter received, please send me the third letter
Bob: 'L', this is the third letter
After a while
Bob: 'L', this the third letter
Amy: Third letter received, please send me the fourth letter
Bob: 'O', this the forth letter
Amy: ...
......
4-way handshake
Bob: My secret is exposed, now, you know my heart.
Amy: OK. I have nothing to say.
Bob: OK.
UDP
Bob: I LOVE U
Amy received: OVI L E
TCP is more reliable than UDP with even message order guaranteed, that's no doubt why UDP is more lightweight and efficient.
The Law of Leaky Abstractions
by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html
Short and simple differences between Tcp and Udp protocol:
1) Tcp - Transmission control protocol and Udp - User datagram protocol.
2) Tcp is reliable protocol, Where as Udp is a unreliable protocol.
3) Tcp is a stream oriented, where as Udp is a message oriented protocol.
4) Tcp is a slower than Udp.
This sentence is a UDP joke, but I'm not sure that you'll get it. The below conversation is a TCP/IP joke:
A: Do you want to hear a TCP/IP joke?
B: Yes, I want to hear a TCP/IP joke.
A: Ok, are you ready to hear a TCP/IP joke?
B: Yes, I'm ready to hear a TCP/IP joke.
A: Well, here is the TCP/IP joke.
A: Did you receive a TCP/IP joke?
B: Yes, I **did** receive a TCP/IP joke.
TCP and UDP are transport layer protocol, Layer 4 protocol in OSI(open systems interconnection model). The main difference along with pros and cons are as following.
TCP
PROS:
Acknowledgment
Guaranteed Delivery
Connection based
Ordered packets
Congestion control
CONS:
Larger Packet
More bandwidth
Slower
Statefull
Consume memory
UDP
PROS:
Packets are smaller
Consume less bandwidth
Faster
Stateless
CONS:
No acknowledgment
No guaranteed delivery
Connectionless
No congestion control
No order packet
TLDR;
TCP - stream-oriented, requires a connection, reliable, slow
UDP - message-oriented, connectionless, unreliable, fast
Before we start, remember that all disadvantages of something are a continuation of its advantages. There only a right tool for a job, no panacea. TCP/UDP coexist for decades, and for a reason.
TCP
It was designed to be extremely reliable and it does its job very well. It's so complex because it accomplishes a hard task: providing a reliable transport over the unreliable IP protocol.
Since all TCP's complex logic is encapsulated into the network stack, you are free from doing lots of laborious, error-prone low-level stuff in the application layer.
When you send data over TCP, you write a stream of bytes to the socket at the sender side where it gets broken into packets, passed down the stack and sent over the wire. On the receiver side packets get reassembled again into a continous stream of bytes.
Maintaining this nice abstraction has a cost in terms of complexity and performance. If the 1st packet from the byte stream is lost, the receiver will delay processing of subsequent packets even those have already arrived (the so-called "head of line blocking").
In addition, in order to be reliable, TCP implements this:
TCP requires an established connection, which requires 3 round-trips ("infamous" 3-way handshake)
TCP has a feature called "slow start" when it gradually ramps up the transmission rate after establishing a connection to allow a receiver to keep up with data rate
Every sent packet has to be acknowledged or else a sender will stop sending more data
And on and on and on...
All this is exacerbated in slow unreliable wireless networks because TCP was designed for wired networks where delays are predictable and packet loss is not so common. In addition, like many people already mentioned, for some things TCP just doesn't work at all (DHCP). However, where relevant, TCP still does its work exceptionally well.
Using a mail analogy a TCP session is similar to telling a story to your secretary who breaks it into mails and sends over a crappy mail service to a publisher. On the other side another secretary assembles mails into a single piece of text. Some mails get lost, some get corrupted, so a very complex procedure is required for reliable delivery and your 10-page story can take a long time to reach your publisher.
UDP
UDP, on the other hand, is message-oriented, so a receiver writes a message (packet) to the socket and then it gets transmitted to a receiver as-is, without any splitting/assembling in the transport layer.
Compared to TCP, its specification is very straightforward. Essentially, all it does for you is adding a checksum to the packet so a receiver can detect its corruption. Everything else must be implemented by you, a software developer. Now read the voluminous TCP spec and try thinking of re-implementing even a small subset of it.
Some people went this way and got very decent results, to the point that HTTP/3 uses QUIC - a protocol based on UDP. However, this is more of an exception. Common applications of UDP are audio/video streaming and conferencing applications like Skype, Zoom or Google Hangout where loosing packets is not so important compared to a delay introduced by TCP.
Simple Explanation by Analogy
TCP is like this.
Imagine you have a pen-pal on Mars (we communicated with written letters back in the good ol' days before the internet).
You need to send your pen pal the seven habits of highly effective people. So you decide to send it in seven separate letters:
Letter 1 - Be proactive
Letter 2 - Begin with the end in mind...
etc.
etc..Letter 7 - Sharpen the Saw
Requirements:
You want to make sure that your pen pal receives all your letters - in order and that they arrive perfectly. If your pen pay receives letter 7 before letter 1 - that's no good. if your pen pal receives all letters except letter 3 - that also is no good.
Here's how we ensure that our requirements are met:
Confirmation Letter: So your pen pal sends a confirmation letter to say "I have received letter 1". That way you know that your pen pal has received it. If a letter does not arrive, or arrives out of order, then you have to stop, and go back and re-send that letter, and all subsequent letters.
Flow Control: Around the time of Xmas you know that your pen pal will be receiving a lot of mail, so you slow down because you don't want to overwhelm your pen pal. (Your pen pal sends you constant updates about the number of unread messages there are in penpal's mailbox - if your pen pal says that the inbox is about to explode because it is so full, then you slow down sending your letters - because your pen pal won't be able to read them.
Perfect arrival. Sometimes while you send your letter in the mail, it can get torn, or a snail can eat half of it. How do you know that all your letter has arrived in perfect condition? Well your pen pal will give you a mechanism by which you can check whether they've got the full letter and that it was the exactly the letter that you sent. (e.g. via a word count etc. ). a basic analogy.

Just curious what goes into the decision between using UDP and TCP when creating an online game

As the title suggests, I was wondering how one decides which protocol to implement. So far I understand that UDP can make for faster transmission of data but with the order it's sent in neglected and it doesn't monitor if the data is even received. To my knowledge TCP is safer and is used when data has to be precise and the reception time doesn't have to be as swift. But I noticed that different online games use different protocols even though all of them games play quite fluently(which I'm assuming means fast data transfer.) So I'm wondering how can you tell which is used, and why is that protocol used?
Thanks
Warning: incoming oversimplification. Still, this should help you understand.
TCP is reliable. If you send data, it will either get there in one piece and in perfect order, or it won't get there. This reliability comes at a cost of more traffic overhead, because the receiver has to acknowledge its receipt to the sender, and the sender may send the same data multiple times to ensure correct delivery.
UDP is unreliable, but with no such overhead. The sender tosses packets at the receiver. Packets that do arrive are still guaranteed to arrive in one piece, but not all packets are guaranteed to arrive. UDP is useful when you can afford transmission loss and the overhead of TCP is too great to justify the reliability.
Examples of uses for UDP include real-time content streaming (video/audio) and continuous state updates (e.g., packets notifying the client of the state of various objects in your game universe). In general, these are adequate targets because data becomes irrelevant very quickly as it is replaced with new data. Better to keep throwing bits and chugging along than to worry about intact arrival of past data that may no longer matter.
On the other hand, something like authentication, a content updating system, or in-game chat would strongly benefit from a more reliable TCP connection, as latency is far less important than integrity.
The reliable way to tell which protocol is used is to use a network packet sniffer that records your network traffic, record some of the game related traffic and look at the protocol name. One example of a free and simple network sniffer is Wireshark (formerly Ethereal).
The UDP vs TCP decision will probably (I say probably as I am not a professional game dev, just a hobby dev) boil down to the amount of traffic you expect to send/receive, the networking conditions, the durability of the program in case of packet loss and the expected number of concurrent users.
A turn based strategy game, for example chess, in which each player need not send much more than their moves and occasional chat messages, would benefit from TCP. A first-person shooter with dozens of players in a 3D might generate a lot of traffic over a long time but might not suffer if a few packets now and then are lost, making it an ideal candidate for UDP.
Then again, some games might even use a combination of TCP and UDP for tasks with different requirements in speed and reliability.
Don't think of it as "UDP is faster" and "TCP is slower", because that's just wrong. The big difference is that bad packets are just dropped in UDP. The receiver UDP implementation won't have to wait for the dropped packet to be retransmitted and received before delivering any subsequent ones to the application.
In TCP, even if your machine has the next packet after the dropped one in a buffer, it won't be able to deliver it to the application until the sender retransmits the one that was dropped.
TCP: deliver data to app in order, automatic retransmit
UDP: deliver data to app in any order, no retransmit
UDP mostly makes sense if the packets are self contained. If you have to reassembly multiple UDP packets into one, you should probably use TCP.

Can UDP retransmit lost data?

I know the protocol doesn't support this but is it common for clients that require some level of reliability to build into their application a method for requesting retransmission of a packet if found to be corrupt?
It is common for clients to implement reliability on top of UDP if they need reliability (or sometimes just some reliability) but not any of the other things that TCP offers, for example strict in-order delivery, and if they want, at the same time, low latency (or multicast, where it works).
In general, you will only want to use reliable UDP if there are urgent reasons (very low latency and high speed needed, e.g. for a twitch game). In every "normal" case, simply using TCP will serve you equally well or better.
Also note that it is easy to implement your own stack on top of UDP that performs worse than TCP.
See enet for an example of a library that implements reliability (and some other features) on top of UDP (Raknet or HawkNL would be other examples).
You might want to look at the answers to this question: What do you use when you need reliable UDP?
Of course. You can build a reliable protocol (like TCP) on top of UDP.
Example
Imagine you are building a fileserver:
* read the file using blocks of 1024 bytes
* construct an UDP packet with payload: 4 bytes for the "position" in the file, 4 bytes for the "length" of the contents of the packet.
The receiver now receives UDP packets. If he gets following packets:
* 0-1024: DATA
* 1024-2048: DATA
* 3072-4096: DATA
it realises a packet got missing, and asks the sending application to resend the part between 2048 and 3072.
This is a very basic example to explain your application code needs to deal with the packet construction and payload interpretation. Don't use it, it does not take edge cases (last packet, checksums for corrupted packets, ...) into account.
Short answer: No.
Long answer: UDP doesn't care for packet loss. If an UDP packet arrives and has a bad checksum, it is simply dropped. Neither the sender of the packet is informed about this, nor the recipient is informed. It is only dropped, that's all that happens. Also UDP packets are not numbered, so if you send four packets and only three arrive at the recipient, the recipient cannot know that there used to be four and one is missing. Last but not least, packets are not acknowledged, so the sender will never know if a packet it was sending out ever made it to the recipient or not.
Contrary to this, TCP breaks data into segments, each segment is numbered, so the recipient can know if a segment is missing. Also all segments must be acknowledged to the sender. If the sender receives no acknowledgment for a segment after a certain period of time, it will assume the segment was lost and send it again.
Of course, you can add an own frame header on top of every data fragment you sent over UDP, that way your application code can number the sent fragments and you can implement an acknowledgement-resent strategy in your code but the question is: Will this really be better than what TCP is already offering for free? Even if it would be equally good, save yourself the time and just use TCP. A lot of people already thought they can do better than TCP and usually they realize in the end, actually they cannot. TCP has its weaknesses but in general it is pretty good at what it does.

Resources