Path: blob/main/share/doc/psd/20.ipctut/dgramsend.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 <netdb.h>31#include <stdio.h>3233#define DATA "The sea is calm tonight, the tide is full . . ."3435/*36* Here I send a datagram to a receiver whose name I get from the command37* line arguments. The form of the command line is dgramsend hostname38* portnumber39*/4041main(argc, argv)42int argc;43char *argv[];44{45int sock;46struct sockaddr_in name;47struct hostent *hp, *gethostbyname();4849/* Create socket on which to send. */50sock = socket(AF_INET, SOCK_DGRAM, 0);51if (sock < 0) {52perror("opening datagram socket");53exit(1);54}55/*56* Construct name, with no wildcards, of the socket to send to.57* Gethostbyname() returns a structure including the network address58* of the specified host. The port number is taken from the command59* line.60*/61hp = gethostbyname(argv[1]);62if (hp == 0) {63fprintf(stderr, "%s: unknown host\en", argv[1]);64exit(2);65}66bcopy(hp->h_addr, &name.sin_addr, hp->h_length);67name.sin_family = AF_INET;68name.sin_port = htons(atoi(argv[2]));69/* Send message. */70if (sendto(sock, DATA, sizeof(DATA), 0, &name, sizeof(name)) < 0)71perror("sending datagram message");72close(sock);73}747576