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.1 (Berkeley) 05/04/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 22 /* 23 * This program creates a datagram socket, binds a name to it, then reads 24 * from the socket. 25 */ 26 27 main() 28 { 29 int sock, length; 30 struct sockaddr_in name; 31 char buf[1024]; 32 33 /* Create socket from which to read. */ 34 sock = socket(AF_INET, SOCK_DGRAM, 0); 35 if (sock < 0) { 36 perror("opening datagram socket"); 37 exit(-1); 38 } 39 /* Create name with wildcards. */ 40 name.sin_family = AF_INET; 41 name.sin_addr.s_addr = INADDR_ANY; 42 name.sin_port = 0; 43 if (bind(sock, &name, sizeof(name))) { 44 close(sock); 45 perror("binding datagram socket"); 46 } 47 /* Find assigned port value and print it out. */ 48 length = sizeof(name); 49 if (getsockname(sock, &name, &length)) { 50 close(sock); 51 perror("getting socket name"); 52 } 53 printf("Socket has port #%d\en", ntohs(name.sin_port)); 54 /* Read from the socket */ 55 if (read(sock, buf, 1024, 0) < 0) 56 perror("receiving datagram packet"); 57 printf("-->%s\en", buf); 58 close(sock); 59 } 60