Connected UDP sockets can also be used to determine out-of-office interfaces for a specific destination. This is caused by a side effect of the Connect function applied to the UDP socket: The kernel chooses the local IP address. This local IP address is selected by searching the routing table for the destination IP address and then selecting the primary IP address of the interface.
Note: The location of the GetSockName function call.
#include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #includ E <string.h> #define Serv_port 3333 #define MAXLINE 1024 #define ERR_EXIT (m) \ do \ { \ perror (m); \ exit (exit_failure);
\} while (0) typedef struct SOCKADDR SA;
int main (int argc, char **argv) {int sockfd;
Socklen_t Len,peer_len;
struct sockaddr_in cliaddr, servaddr,peer_addr;
if (argc!= 2) err_exit ("Usage:udpcli <IPaddress>");
SOCKFD = socket (af_inet, SOCK_DGRAM, 0);
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
Servaddr.sin_port = htons (Serv_port);
Inet_pton (Af_inet, argv[1], &servaddr.sin_addr);
Connect (SOCKFD, (SA *) &servaddr, sizeof (SERVADDR));
len = sizeof (CLIADDR);
GetSockName (SOCKFD, (SA *) &cliaddr, &len);
printf ("Local address%s and port =%d\n", Inet_ntoa (CLIADDR.SIN_ADDR), Ntohs (Cliaddr.sin_port));
Getpeername (SOCKFD, (SA *) &peer_addr, &peer_len);
printf ("Peer address%s and port =%d\n", Inet_ntoa (PEER_ADDR.SIN_ADDR), Ntohs (Peer_addr.sin_port));
Exit (0); }
Run Result:
huangcheng@ubuntu:~$./CLI 192.168.2.103 Local address
192.168.2.103 and port = 53271 Peer Address
192.168.2.103 and port = 3333
Author: csdn Blog Ctthuangcheng
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/