1 .\" Copyright (c) 1986 Regents of the University of California. 2 .\" All rights reserved. The Berkeley software License Agreement 3 .\" specifies the terms and conditions for redistribution. 4 .\" 5 .\" @(#)dgramread.c 6.3 (Berkeley) 05/08/86 6 .\" 7 #include <sys/types.h> 8 #include <sys/socket.h> 9 #include <netinet/in.h> 10 #include <stdio.h> 11 12 /* 13 * In the included file <netinet/in.h> a sockaddr_in is defined as follows: 14 * struct sockaddr_in { 15 * short sin_family; 16 * u_short sin_port; 17 * struct in_addr sin_addr; 18 * char sin_zero[8]; 19 * }; 20 * 21 * This program creates a datagram socket, binds a name to it, then reads 22 * from the socket. 23 */ 24 main() 25 { 26 int sock, length; 27 struct sockaddr_in name; 28 char buf[1024]; 29 30 /* Create socket from which to read. */ 31 sock = socket(AF_INET, SOCK_DGRAM, 0); 32 if (sock < 0) { 33 perror("opening datagram socket"); 34 exit(1); 35 } 36 /* Create name with wildcards. */ 37 name.sin_family = AF_INET; 38 name.sin_addr.s_addr = INADDR_ANY; 39 name.sin_port = 0; 40 if (bind(sock, &name, sizeof(name))) { 41 perror("binding datagram socket"); 42 exit(1); 43 } 44 /* Find assigned port value and print it out. */ 45 length = sizeof(name); 46 if (getsockname(sock, &name, &length)) { 47 perror("getting socket name"); 48 exit(1); 49 } 50 printf("Socket has port #%d\en", ntohs(name.sin_port)); 51 /* Read from the socket */ 52 if (read(sock, buf, 1024) < 0) 53 perror("receiving datagram packet"); 54 printf("-->%s\en", buf); 55 close(sock); 56 } 57