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

📄 vxserver.c

📁 嵌入式VxWorks开发的各种实验源代码以及相关教程
💻 C
字号:
/* 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -