⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unixserver.c

📁 Tornado train workshop的配套实验教材
💻 C
字号:
/* unixServer - reads client requests and sends a reply. */

/* Copyright 1984-1994 Wind River Systems, Inc. */

/*
modification history
--------------------
01c,06apr98,dlk  removed free (pClientInet).
01b,05dec94,bss  cleaned up.  WRS coding conventions enforced. 
01a,???????,???  written.
*/

/*
DESCRIPTION
*/

/* includes */

#include <arpa/inet.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

/* defines */

#define MAX_MSG_LEN 80

#define FOREVER for (;;)		/* for WRS coding conventions */
#define LOCAL static

/* typedefs */

typedef int SOCK_FD;

/* forward declarations */

LOCAL void error ();

/*******************************************************************************
 *
 * main - entry point to unixServer
 *
 * This routine sets up a UDP socket and then sits in an infinite
 * loop reading client messages, printing them to the console, and
 * sending a reply.
 */

main (argc, argv)
	int argc;
	char ** argv;
	{
	short port;
	int					clientAddrLength;
	SOCK_FD				sockFd;
	struct sockaddr_in	clientAddr;
	struct sockaddr_in	srvAddr;
	char				buf [MAX_MSG_LEN];
	char *				reply = "Here is your reply\n";
	u_short				clientPort;
	char *				pClientInet;

	clientAddrLength = sizeof (clientAddr);

	/* Get the server port number */
	if (argc != 2)
		{
		fprintf (stderr, "Usage: %s portNumber\n", argv[0]);
		exit (1);
		}
	port = (short) atoi (argv [1]);

	/* Create a socket */
	if ((sockFd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
		error ("Socket failed");

	/* 
	 * Bind to a well known address. INADDR_ANY says any network
	 * interface will do. hton?() routines put things in network
	 * byte order 
	 */

	bzero ((char *) &srvAddr, sizeof (srvAddr));
	srvAddr.sin_family		= AF_INET;
	srvAddr.sin_port		= htons(port);
	srvAddr.sin_addr.s_addr = INADDR_ANY;

	if (bind (sockFd, &srvAddr, sizeof(srvAddr)) < 0)
		{
		close (sockFd);
		error ("Bind failed");
		}

	FOREVER
		{
		if (recvfrom (sockFd, buf, MAX_MSG_LEN, 0, &clientAddr,
					  &clientAddrLength)  < 0)
			{
			close (sockFd);
			error ("recvfrom failed");
			}

		clientPort = ntohs (clientAddr.sin_port);
		pClientInet = inet_ntoa (clientAddr.sin_addr);

		printf ("Message received from client (port = %d, inet = %s):\n",
				clientPort, pClientInet);
		printf ("%s\n", buf);

		if (sendto (sockFd, reply, strlen(reply) + 1, 0,
					&clientAddr, clientAddrLength) < 0)
			{
			close (sockFd);
			error ("sendto failed");
			}
		}
	}

/*******************************************************************************
 *
 * error - aborts a process on an error 
 *
 * This funcion displays the reason a process crashed 
 * and terminates that process.
 */

LOCAL void error (pStr)
	char * pStr;
	{
	perror (pStr);
	exit (1);
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -