Path: blob/main/share/doc/psd/20.ipctut/dgramread.c
39530 views
.\" Copyright (c) 1986, 19931.\" The Regents of the University of California. All rights reserved.2.\"3.\" Redistribution and use in source and binary forms, with or without4.\" modification, are permitted provided that the following conditions5.\" are met:6.\" 1. Redistributions of source code must retain the above copyright7.\" notice, this list of conditions and the following disclaimer.8.\" 2. Redistributions in binary form must reproduce the above copyright9.\" notice, this list of conditions and the following disclaimer in the10.\" documentation and/or other materials provided with the distribution.11.\" 3. Neither the name of the University nor the names of its contributors12.\" may be used to endorse or promote products derived from this software13.\" without specific prior written permission.14.\"15.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND16.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE17.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE18.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE19.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL20.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS21.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)22.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT23.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY24.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF25.\" SUCH DAMAGE.26.\"27#include <sys/types.h>28#include <sys/socket.h>29#include <netinet/in.h>30#include <stdio.h>3132/*33* In the included file <netinet/in.h> a sockaddr_in is defined as follows:34* struct sockaddr_in {35* short sin_family;36* u_short sin_port;37* struct in_addr sin_addr;38* char sin_zero[8];39* };40*41* This program creates a datagram socket, binds a name to it, then reads42* from the socket.43*/44main()45{46int sock, length;47struct sockaddr_in name;48char buf[1024];4950/* Create socket from which to read. */51sock = socket(AF_INET, SOCK_DGRAM, 0);52if (sock < 0) {53perror("opening datagram socket");54exit(1);55}56/* Create name with wildcards. */57name.sin_family = AF_INET;58name.sin_addr.s_addr = INADDR_ANY;59name.sin_port = 0;60if (bind(sock, &name, sizeof(name))) {61perror("binding datagram socket");62exit(1);63}64/* Find assigned port value and print it out. */65length = sizeof(name);66if (getsockname(sock, &name, &length)) {67perror("getting socket name");68exit(1);69}70printf("Socket has port #%d\en", ntohs(name.sin_port));71/* Read from the socket */72if (read(sock, buf, 1024) < 0)73perror("receiving datagram packet");74printf("-->%s\en", buf);75close(sock);76}777879