0
votes

What is the difference between making a connection with TCP sockets (sock_stream) and UDP sockets (datagram). Up to now, I think like we can create a connection using connect function only for TCP sockets. But, it is possible for making a connection with UDP sockets. Up to now I didn't know about making a connection with UDP sockets. What is the difference between these two?

        int tcpsock = socket(AF_INET, SOCK_STREAM, 0);
        connect(tcpsock,(struct sockaddr*)&sa,sizeof(sa));

        int udpsock = socket(AF_INET, SOCK_DGRAM, 0);
        connect(udpsock,(struct sockaddr*)&sa,sizeof(sa));  // How ?

UDP is connectionless. so if we use UDP how it is possible to make a connection similar to TCP?

I already know about the difference between TCP and UDP. My doubt is, UDP is connectionless then how connect function returns success?

1
Why the C and C++ tags are there?Sourav Ghosh
Have you tried typing "difference between TCP and UDP" into Google, and then reading some of the results?Andrew
"Up to now, I think like we can create a connection using connect function only for tcp socket." Well, that's because the TCP protocol requires that. The UDP protocol is connectionless.πάντα ῥεῖ
@πάνταῥεῖ But connect function returns 0(success) even for udp sockets.mohangraj

1 Answers

3
votes

The connect() function in UDP (a) tells UDP where to send all datagrams, so you can use send() instead of sendto(), and (b) acts as a filter on incoming datagrams, so you can use recv() instead of recvfrom(). It doesn't do anything on the network: it's just a local operation. It always returns zero because it can't fail. However sending to a non-existent target can fail ...

It's all documented.