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