vxserver.c

来自「嵌入式VxWorks开发的各种实验源代码以及相关教程」· C语言 代码 · 共 88 行

C
88
字号
/* vxServer.c - simple UDP demo server */

#include "vxWorks.h"
#include "sockLib.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "inetLib.h"
#include "ioLib.h"
#include "string.h"
#include "stdio.h"
#include "taskLib.h"

typedef int SOCK_FD;

LOCAL void error (char * str);

void vxServer (u_short port)
	{
	int clientAddrLength;
	SOCK_FD sockFd;
	struct sockaddr_in clientAddr;
	struct sockaddr_in srvAddr;
	char inetAddr[INET_ADDR_LEN];
	u_short clientPort;
	char *reply = "Here is your reply\n";
	int val;

	clientAddrLength = sizeof (clientAddr);

	/* 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. htonX()
	 * 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, (struct sockaddr *) &srvAddr,
		sizeof(srvAddr)) < 0 )
		{
		close (sockFd);
		error ("Bind failed");
		}

	FOREVER
		{
		if (recvfrom (sockFd, (char *) &val,
						 sizeof(val), 0,
						 (struct sockaddr *) &clientAddr,
						 &clientAddrLength) < 0)
			{
			close (sockFd);
			error ("recvfrom failed");
			}

		val = ntohl (val);
		inet_ntoa_b (clientAddr.sin_addr, inetAddr);
		clientPort = ntohl (clientAddr.sin_port);

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

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


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

⌨️ 快捷键说明

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