C   23

getsockname

Guest on 18th April 2022 05:56:46 PM

  1. include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. int main(int argc, char **argv) {
  11.   int tempsock = 0, len = 0;
  12.   struct sockaddr_in ssa4;
  13.   struct sockaddr_in UDPssa4;
  14.  
  15.   if((tempsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
  16.     perror("mtr");
  17.     exit(1);
  18.   }
  19.  
  20.   ssa4.sin_port = htons(0);
  21.   ssa4.sin_addr.s_addr = htonl(INADDR_ANY);
  22.   len = sizeof (struct sockaddr);
  23.  
  24.   if(bind( tempsock, (struct sockaddr *) &ssa4, len ) == -1 ) {
  25.     perror("bind");
  26.     exit(1);
  27.   }
  28.  
  29.   if(getsockname(tempsock, (struct sockaddr *) &UDPssa4, &len)) {
  30.     perror("getsockname");
  31.     exit(1);
  32.   }
  33.  
  34.   printf("UDP source addr: %x, port: %d\n", UDPssa4.sin_addr.s_addr,
  35.       UDPssa4.sin_port);
  36.  
  37.   /* close it */
  38.   if(close(tempsock)) {
  39.     perror("close");
  40.     exit(1);
  41.   }
  42.  
  43.   return 0;
  44. }

Raw Paste


Login or Register to edit or fork this paste. It's free.