|
|
1.1 root 1: /*
2: * Copyright (c) 1986 The Regents of the University of California.
3: * All rights reserved.
4: *
5: * Redistribution and use in source and binary forms are permitted
6: * provided that the above copyright notice and this paragraph are
7: * duplicated in all such forms and that any documentation,
8: * advertising materials, and other materials related to such
9: * distribution and use acknowledge that the software was developed
10: * by the University of California, Berkeley. The name of the
11: * University may not be used to endorse or promote products derived
12: * from this software without specific prior written permission.
13: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14: * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15: * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16: */
17:
18: #ifndef lint
19: char copyright[] =
20: "@(#) Copyright (c) 1986 The Regents of the University of California.\n\
21: All rights reserved.\n";
22: #endif /* not lint */
23:
24: #ifndef lint
25: static char sccsid[] = "@(#)dgramread.c 6.4 (Berkeley) 3/7/89";
26: #endif /* not lint */
27:
28: #include <sys/types.h>
29: #include <sys/socket.h>
30: #include <netinet/in.h>
31: #include <stdio.h>
32:
33: /*
34: * In the included file <netinet/in.h> a sockaddr_in is defined as follows:
35: * struct sockaddr_in {
36: * short sin_family;
37: * u_short sin_port;
38: * struct in_addr sin_addr;
39: * char sin_zero[8];
40: * };
41: *
42: * This program creates a datagram socket, binds a name to it, then reads
43: * from the socket.
44: */
45: main()
46: {
47: int sock, length;
48: struct sockaddr_in name;
49: char buf[1024];
50:
51: /* Create socket from which to read. */
52: sock = socket(AF_INET, SOCK_DGRAM, 0);
53: if (sock < 0) {
54: perror("opening datagram socket");
55: exit(1);
56: }
57: /* Create name with wildcards. */
58: name.sin_family = AF_INET;
59: name.sin_addr.s_addr = INADDR_ANY;
60: name.sin_port = 0;
61: if (bind(sock, &name, sizeof(name))) {
62: perror("binding datagram socket");
63: exit(1);
64: }
65: /* Find assigned port value and print it out. */
66: length = sizeof(name);
67: if (getsockname(sock, &name, &length)) {
68: perror("getting socket name");
69: exit(1);
70: }
71: printf("Socket has port #%d\en", ntohs(name.sin_port));
72: /* Read from the socket */
73: if (read(sock, buf, 1024) < 0)
74: perror("receiving datagram packet");
75: printf("-->%s\en", buf);
76: close(sock);
77: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.