11.15 udp_connect
Function
Our udp_connect function creates a
connected UDP socket.
#include "unp.h"
|
int udp_connect (const char
*hostname, const char
*service);
|
Returns: connected socket descriptor if OK, no
return on error
|
With a connected UDP socket, the final two
arguments required by udp_client are no longer needed. The
caller can call write instead of sendto, so our
function need not return a socket address structure and its
length.
Figure
11.17 shows the source code.
Figure 11.17
udp_connect function: creates a connected UDP socket.
lib/udp_connect.c
1 #include "unp.h"
2 int
3 udp_connect (const char *host, const char *serv)
4 {
5 int sockfd, n;
6 struct addrinfo hints, *res, *ressave;
7 bzero (&hints, sizeof (struct addrinfo));
8 hints.ai_family = AF_UNSPEC;
9 hints.ai_socktype = SOCK_DGRAM;
10 if ( (n = getaddrinfo (host, serv, &hints, &res)) != 0)
11 err_quit ("udp_connect error for %s, %s: %s",
12 host, serv, gai_strerror (n));
13 ressave = res;
14 do {
15 sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
16 if (sockfd < 0)
17 continue; /* ignore this one */
18 if (connect (sockfd, res->ai_addr, res->ai_addrlen) == 0)
19 break; /* success */
20 Close (sockfd); /* ignore this one */
21 } while ( (res = res->ai_next) ! = NULL);
22 if (res == NULL) /* errno set from final connect () */
23 err_sys ("udp_connect error for %s, %s", host, serv);
24 freeaddrinfo (ressave);
25 return (sockfd);
26 }
This function is nearly identical to
tcp_connect. One difference, however, is that the call to
connect with a UDP socket does not send anything to the
peer. If something is wrong (the peer is unreachable or there is no
server at the specified port), the caller does not discover that
until it sends a datagram to the peer.
|