/* Show how to get the remote and local IPs from a UDP socket connection */ /* For sockets */ #include #include #include /* For INET sockets */ #include #include /* Printing info about connections */ #include #include #include #include #define TEST_UDP_PORT 6667 int main(void) { int s; struct sockaddr_in bindsockaddr; const long true = 1L; s = socket(AF_INET,SOCK_DGRAM,0); /* Get information about each incoming packet */ setsockopt(s, IPPROTO_IP, IP_PKTINFO, &true, sizeof(1L)); bindsockaddr.sin_family = AF_INET; bindsockaddr.sin_addr.s_addr = htonl(INADDR_ANY); bindsockaddr.sin_port = htons(TEST_UDP_PORT); bind(s,(struct sockaddr *)&bindsockaddr,sizeof(bindsockaddr)); fprintf(stderr,"Now listening on udp port %d\n",TEST_UDP_PORT); while (1) { struct sockaddr_in client; int templen = sizeof(struct sockaddr_in); struct msghdr msg; char buf[512]; struct { struct cmsghdr cm; int len; struct in_addr address; } ip_msg; /* Zero out the structures before we use them */ /* This sets several key values to NULL */ memset(&msg,0,sizeof(msg)); memset(&ip_msg,0,sizeof(ip_msg)); /* Initialize the message structure */ msg.msg_control = &ip_msg; msg.msg_controllen = sizeof(ip_msg); /* Get info about the incoming packet */ recvmsg(s, &msg, MSG_PEEK); /* Receive the incoming packet */ recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&client, &templen); fprintf(stderr, "Client: %s, port %d\r\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); fprintf(stderr, "Server: %s, port %d\r\n", inet_ntoa(ip_msg.address), TEST_UDP_PORT); /* If this were a real application, we'd probably want to do something intelligent with buf here */ } }