0

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?

mohangraj
  • 9,842
  • 19
  • 59
  • 94

1 Answers1

3

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.

user207421
  • 305,947
  • 44
  • 307
  • 483