Advertisement
rfmonk

datainet.c

Nov 22nd, 2013
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <stdio.h>
  5.  
  6. /*
  7.  * In the included file <netinet/in.h> a sockaddr_in is defined as follows:
  8.  *  struct sockaddr_in {
  9.  *  short sin_family;
  10.  *  u_short sin_port;
  11.  *  struct in_addr sin_addr;
  12.  *  char sin_zero[8];
  13.  * };
  14.  *
  15.  * This program creates a datagram socket, binds a name to it, then reads
  16.  * from the socket.
  17.  */
  18.  
  19. main()
  20. {
  21.     int sock, length;
  22.     struct sockaddr_in name;
  23.     char buf[1024];
  24.  
  25.     /* Create socket from which to read. */
  26.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  27.     if (sock < 0) {
  28.         perror("opening datagram socket");
  29.         exit(1);
  30.     }
  31.     /* Create name with wildcards. */
  32.     name.sin_family = AF_INET;
  33.     name.sin_addr.s_addr = INADDR_ANY;
  34.     if (bind(sock, &name, sizeof(name))) {
  35.         perror("binding datagram socket");
  36.         exit(1);
  37.     }
  38.     /* Find assigned port value and print it out. */
  39.     length = sizeof(name);
  40.     if (getsockname(sock, &name, &length)) {
  41.         perror("getting socket name");
  42.         exit(1);
  43.     }
  44.     printf("Socket has port #%d\n", ntohs(name.sin_port));
  45.     /* Read from the socket */
  46.     if (read(sock, buf, 1024) < 0)
  47.         perror("receiving datagram packet");
  48.     printf("-->%s\n", buf);
  49.     close(sock);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement