欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vxworks和windows端的socket udp通信

程序员文章站 2022-06-29 18:58:40
...

Vxworks接收端 

#include <stio.h>
#include <sockLib.h>
#include <inetLib.h>

int Mainapp()
{
    INT8 recvBuf[2048] = {0, };
    INT8 recvBuf[2048] = {0, };

    INT32 retCode = 0; 
	UINT32 rxSocket = 0;
	//两个地址结构体
	struct sockaddr_in rxAddr;
	struct sockaddr_in txAddr;
    UINT32 port = 50000;
	INT32 rxAddrSize = 0;
	INT32 txAddrSize = 0;
	INT32 rxLen = 0;
	INT32 txLen = 0;
	
	//创建套接字,UDP
	rxSocket = socket(AF_INET, SOCK_DGRAE, IPPROTO_UDP);
    
	//地址赋值
	txAddrSize = sizeof(txAddr);
	rxAddrSize = sizeof(rxAddr);
	rxAddr.sin_family = AF_INET;
	rxAddr.sin_port = htons(port);
	rxAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    //绑定套接字
	retCode = bind(rxSocket, (struct sockaddr *)&rxAddr, rxAddrSize);
	if(ERROR == retCode)
	{
	   printf("tSocketCfg bind error\n!");
	   return;
	}
    //不断接受消息
	while(1)
	{
	   //清理recvbuf
	   memset(recvbuf,0,sizeof(recvBuf));
	   //接受数据
       rxLen = recvfrom(rxSocket, (char*)&recvBuf[0], sizeof(recvBuf),0,(struct sockaddr*)&txAddr, &txAddrSize);
	   if(ERROR == rxLen)
	   {
	      printf("tSocketCfg recvfrom error\n");
		  continue;
	   }
      printf("Recv :%s\n",recvBuf);
	  sprintf(sendBuf, "I recved %s\n", recvBuf);
      //回传
	  txLen = sendto(rxSocket, (char*)&sendBuf[0], 200, 0, (struct sockaddr*)&txAddr,txAddrSize);
      if(ERROR == txLen)
	  {
	      printf("tSocketCfg send fail!");
	  }
	} 
return 0;
}

windows发送端


#include <stdio.h>
#include "winsock2.h"
#pragma comment(lib, "Ws2_32.lib");
int main()
{
   int ret = 0;
   SOCKET hSocket;
   WSADATA wsaData;
   char sendBuf[2048] = "hello world!";
   char recvBuf[2048] = {0, };
   struct sockaddr_in destAddr;
   struct sockaddr_in srcAddr;
   int AddrSize = sizeof(srcAddr);

   WSAStartup(MAKEWORD(2,2), &wsaData);

   hSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

   destAddr.sin_family = AF_INET;
   destAddr.sin_port = htons(50000);
   destAddr.sin_addr.s_addr = inet_addr("10.5.235.245");

   while(1)
   {
      ret = sendto(hSocket, sendBuf ,1000, 0, (struct sockaddr *)&destAddr, sizeof(destAddr));
      if (ret == SOCKET_ERROR)
	  {
         return (-1);
	  }
	  ret = recvfrom(hSockket, recvBuf, 2048, 0, (struct sockaddr *)&srcAddr, &AddrSize);
      if (SOCKET+ERROR == ret)
	  {
        printf("recvfrom error!\n");
		return(-3);
	  }
	  
	  printf("recv ip:%s, port:%d, %s\n", inet_ntoa(srcAddr.sin_Addr), ntohs(srcAddr.sin_port),recvBuf);
      Sleep(1000);  
   }

}