What is the role of UDP call Connect

Source: Internet
Author: User
Tags htons

The original link is as follows:

http://blog.csdn.net/wannew/article/details/18218619

Tidy up a bit.
1:UDP can be called using the Connect system


The connect operation in 2:UDP is fundamentally different from the connect operation in TCP.


Calling connect in TCP causes three handshakes, and the client establishes a connection with the server. Calling the connect kernel in UDP simply logs the peer Ip&port.


You can call connect,tcp multiple times in 3:UDP to call connect only once.


There are two uses for UDP multiple calls to connect: 1, specifying a new Ip&port link. 2, disconnect and the previous Ip&port link.


Specify a new link and set the connect second parameter directly.


To disconnect the link, you need to set the sin_family in the second parameter of connect to Af_unspec.


Using connect in 4:UDP can improve efficiency. For the following reasons:


The normal UDP sends two message cores to do the following: #1: Build link # #: send a newspaper # #: Break Link # #: Build link # #: send a delivery article #: Break link


Use the Connect mode of UDP to send two message cores as follows: #1: Build link # #: send a paper message #: Send a paper another point, every time the kernel of sending messages may be to do the routing query.


5: UDP Send Accept message with connect can call Send,write and Recv,read operation. Of course, you can also call Sendto,recvfrom.


When calling SendTo, the fifth argument must be null, and the sixth parameter is 0. Calling the Recvfrom,recv,read system call can only get messages sent to the ip&port of the previous connect.




Benefits of using Connect in UDP: 1: It improves efficiency. 2: High concurrency Service increases system stability. Reason: Assume that client A communicates with the server b,c via UDP that is not connect. For load balancing, We have a and b,c alternating communication. A and B communication Ipa:porta <----> IPB:PORTB;


A and C communication Ipa:porta ' <----&GT;IPC:PORTC


Assuming that PORTa is the same as PORTa ' (which happens in large concurrency), then there is the possibility of a message waiting for B, but a message from C. causes a ticker error. The solution is to use the UDP communication method of Connect. Create two UDP in a Then connect to b,c separately.


================




http://hi.baidu.com/rwen2012/item/545a39ba741307d085dd7957


Connect (ZT) in UDP programming
Standard UDP client opened a set of interfaces, the general use of sendto and RECVFROM functions to send data, recently saw NtpClient code inside is the use of the Send function direct method, analysis, the original UDP sent data there are two ways for everyone to choose, By the way, the UDP connect usage is also explained clearly. Method One: Socket----->sendto () or Recvfrom () method Two: Socket----->connect ()----->send () or recv () The first thing to see here is that you can use connect in UDP, but what is the difference between these two methods? First, the definitions of these four send functions are listed: int send (int s, const void *msg, size_t len, int flags); int sendto (int s, const void *msg, size_t len, int flags, const struct SOCKADDR *to, socklen_t tolen); int recv (int s, void *buf, size_t len, int flags), int  recvfrom (int  s, void *buf, size_t len, int flags, struct sockaddr *from, &NB Sp;socklen_t *fromlen); from their definition, sendto and recvfrom specify the address when sending and receiving, and send and recv do not, then their address is specified there, the answer is Connect.int   Connect (int  sockfd,  const  struct sockaddr *serv_addr, socklen_t addrlen); In UDP programming, if you only send to one address, Then you can use Send and recv to specify their destination address with connect before using them. The Connect function is this role in UDP, and it is useless to use it to detect whether the UDP port is open or not. Below is the code struct SOCKADDR_IN sa_dest;bzero ((char *) sa_dest, sizeof (*sa_dest)) in NtpClient; sa_dest->sin_family=aF_inet;if (Stuffnetaddr (& (SA_DEST-&GT;SIN_ADDR), host)) return 1;sa_dest->sin_port=htons (port), if (Connect ( USD, (struct sockaddr *) &sa_dest,sizeof (sa_dest)) (==-1) {perror ("connect"); return 1;} Return 0;=================================
Unless the socket interface is connected, the asynchronous error is not returned to the UDP socket interface, we can indeed call connect to the UDP socket interface, but the result is very different from the TCP connection: There is no three-way handshake process.
Instead, the kernel simply checks for an immediately known error (such as an apparently unreachable destination), logs the IP address and port number of the peer (taken from the socket address structure passed to connect), and immediately returns to the calling process.
For a connected UDP socket interface, there are three changes compared to the default non-connected sockets: 1 We can no longer specify the host IP and port number for the output operation, that is, we do not use sendto, instead of write or send, Any content that is written to the connected UDP socket interface is automatically sent to the protocol address specified by connect (for example, IP address and port number) 2 We do not need to use recvfrom to learn the sender of the datagram, instead of using READ,RECV or recvmsg, on a connected UDP socket interface , the datagram returned by the kernel for an input operation is simply a datagram from the protocol address specified by connect. The destination is the local protocol address of the UDP socket interface, but the origin is not a datagram of the protocol address that the socket was previously connected to, and will not be delivered to the socket. This restricts a connected UDP socket interface and can only exchange datagrams with one peer. 3 asynchronous errors thrown by the connected UDP socket interface are returned to the process they are in. Instead, we have said that the UDP socket interface does not receive any asynchronous errors to a UDP socket interface.
Multiple calls to connect a process that has a connected UDP socket interface can be one of the following 2 purposes: A. Specify a new IP address and port number; b. Disconnect the socket interface The first purpose (that is, to specify a new peer to a connected UDP socket) is different from the use of connect in the TCP socket interface: For TCP socket interfaces, connect can only be called once. To disconnect a connected UDP socket interface, we call connect again to set the address cluster member (sin_family) of the socket address structure to AF_UNSPEC. Doing so may return a eafnosupport error, but it doesn't matter. Causes the socket interface to disconnect from the process that calls connect on the connected UDP socket interface.
================================= hassome of the following benefits: 1) selected to the end, the kernel will only help the object to the end of the datagram sent to the socket interface, so in a certain environment can improve security; 2) will return an asynchronous error, if the peer does not start, by default the packets sent by the corresponding ICMP package will not be given to the calling process, if using Connect, Hehe 3) Send two bags do not first disconnect and then connect, improve the efficiency. Let's do an experimental test, get a UDP back-up server, and send back all the incoming data:
[Email protected]:~/d/lab$ cat Rollbackserver.cpp
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace Std;
int main ()
{
int Socklistener,nmsglen;
Char szbuf[1024];
struct sockaddr_in addrlistener;
Socklen_t Addrlen;
addrlen=sizeof (struct sockaddr_in);
Bzero (&addrlistener,sizeof (Addrlistener));
Addrlistener.sin_family=af_inet;
Addrlistener.sin_port=htons (8000);


if ((Socklistener=socket (af_inet,sock_dgram,0)) ==-1)
{
Perror ("Error in getting a socket");
Exit (1);
}


if (Bind (Socklistener, (struct sockaddr*) &addrlistener,sizeof (Addrlistener)) ==-1)
{
Perror ("Bind a listener for a socket");
Exit (2);
}


struct sockaddr_in addrclient;
cout<< "Callback server begin to listen" <<endl;
while (true)
{
Nmsglen=recvfrom (socklistener,szbuf,1024,0, (struct sockaddr*) &addrclient,&addrlen);
if (nmsglen>0)
{
szbuf[nmsglen]= ' + ';
cout<< "Send back:" <<szBuf<<endl;
SendTo (socklistener,szbuf,nmsglen,0, (struct sockaddr*) &addrclient,addrlen);
}
}


}




Write a client, bind a port, and then connect to the server side. Accept the keyboard input at any time and send to the server side, accept the port arrival data and print at any time. If there is no connection, the data sent to this port is accepted, but what happens when you call connect?
a-desktop:~/d/lab$ Cat Udpclient.cpp
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
using namespace Std;
int main ()
{
int sockclient,nmsglen,nready;
Char szrecv[1024],szsend[1024],szmsg[1024];
struct sockaddr_in addrserver,addrclient,addrlocal;
Socklen_t Addrlen;
Fd_set sethold,settest;


Sockclient=socket (af_inet,sock_dgram,0);
addrlen=sizeof (struct sockaddr_in);
Bzero (&addrserver,sizeof (addrserver));
Addrserver.sin_family=af_inet;
ADDRSERVER.SIN_ADDR.S_ADDR=INET_ADDR ("127.0.0.1");
Addrserver.sin_port=htons (8000);


Addrlocal.sin_family=af_inet;//bind to a local port
Addrlocal.sin_addr.s_addr=htonl (Inaddr_any);
Addrlocal.sin_port=htons (9000);
if (Bind (sockclient, (struct sockaddr*) &addrlocal,sizeof (addrlocal)) ==-1)
{
Perror ("Error in binding");
Exit (2);
}


if (Connect (sockclient, (struct sockaddr*) &addrserver,sizeof (addrserver)) ==-1)
{
Perror ("Error in connecting");
Exit (1);
}


Fd_zero (&sethold);
Fd_set (Stdin_fileno,&sethold);
Fd_set (Sockclient,&sethold);
cout<< "can type in sentences any time" <<endl;
while (true)
{
Settest=sethold;
Nready=select (Sockclient+1,&settest,null,null,null);
if (Fd_isset (0,&settest))
{
Nmsglen=read (0,szmsg,1024);
Write (Sockclient,szmsg,nmsglen);
}
if (Fd_isset (sockclient,&settest))
{
Nmsglen=read (sockclient,szrecv,1024);
szrecv[nmsglen]= ' + ';
cout<< "READ:" <<szRecv<<endl;
}


}


}
Finally, a "third party", the second port to send a datagram. See if she will be a loyal guardian of affection:
[Email protected]:~/d/lab$ cat Clienta.cpp
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace Std;
int main ()
{
socklen_t addrlen=sizeof (struct sockaddr_in);
struct sockaddr_in addrserver;
Char szmsg[1024];
int sockclient;


Addrserver.sin_family=af_inet;
ADDRSERVER.SIN_ADDR.S_ADDR=INET_ADDR ("127.0.0.1");
Addrserver.sin_port=htons (9000);


Sockclient=socket (af_inet,sock_dgram,0);
while (true)
{
static int id=0;
snprintf (Szmsg,sizeof (szmsg), "This is%d", id++);
SendTo (Sockclient,szmsg,strlen (szmsg), 0, (struct sockaddr*) &addrserver,sizeof (addrserver));
Sleep (1);
}
}






Experimental results:
Now run the first program, run the third program, and then run the second program.
Server-side:


[Email protected]:~/d/lab$./rollback
Callback server begin to listen
Send Back:xinheblue likes playing


Send Back:and listenning to music




Second program:
[Email protected]:~/d/lab$./udpclient
You can type in sentences any time
Xinheblue likes playing
Read:xinheblue likes playing


and listenning to music
Read:and listenning to music




The result proves that the second program calls connect and does not dump the packets sent from the third program.
/////////////////
http://bbs.csdn.net/topics/290070552 about UDP Socket interface after connect ()
There's one thing I've never understood, how does the UDP socket interface after connect do the test of sending data successfully or not? Direct sendto cannot be detected, why can I write after connect?


After the UDP Connect kernel logs the destination IP and PORT in your connect, you can read and call write while the kernel will tell you the asynchronous error of the connected socket
Like what:
Once an error is sent to a nonexistent host, you receive an ICMP host unreachable kernel that will handle this ICMP message and write the error


If it is not connect, if the kernel will receive this ICMP (obviously this is definitely not what we can control, the router), but it is not care of this stuff.




As for the reason:
It is said that there is a certain delay from sending to receiving ICMP, if it is Sendto you write the datagram to two destination address 1 success 1 failure If the kernel receives an ICMP packet at this time, it does not know which Sendto it is.


It seems that UNP said, but feel ICMP if return, there should be sent UDP header, which contains the destination IP and destination port, it is not possible to distinguish it? I didn't see it completely. Expect a stronger explanation ...
/////////////////////////////
http://blog.csdn.net/rissonal/article/details/2816690


Go to]UDP and socket functions (bound ports)
UDP is a non-connected protocol, so the socket function connect seems meaningless to UDP,
But that's not the case.


A socket has several properties, including protocol, local address/port, destination address/port.


For UDP, the socket function establishes a socket, and the BIND function indicates the local address/port
(including Addr_any, all local network interfaces); Connect can be used to indicate a destination
address/port;


In general, the UDP client will send the data directly with the SendTo function after the socket has been established, requiring
Specify the destination address/port in the parameters of the SendTo function. If a UDP client has established a plug-in
After the port, the destination address/port is first indicated by the Connect function, which can then be sent using the Send function
Data, since the Send function already knows the address/port of the other, it can be used with getsockname
To this information.


The UDP client sends the data directly with the SendTo function after the socket is established, and an operation is implied.
That is, before the data is sent, UDP will first select a separate UDP port for the socket (at 1024
-5000) to place the socket in a bound state. If a UDP client has established a socket
It is also possible to specify the local address/port with the BIND function, which forces the use of UDP to refer to the
Send data to the designated port. (In fact, UDP does not matter to the server and the client, where the boundaries have been modeled
It's burnt. )


The UDP server can also use Connect, as described above, connect can be used to indicate the destination address
/port; This causes the server to accept requests only for a particular host.

What is the role of UDP call Connect (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.