C++怎么编程实现指定IP和端口的数据转发到另一个指定的IP上?

2021-11-04 教育 279阅读
首先你要确定要用什么协议来传送TCP还是UDP给你发个基于UDP协议的吧#include
#include"winsock2.h"

voidmain(){

WSADATAwsaData;
SOCKETSendSocket;
sockaddr_inRecvAddr;
intPort=27015;
charSendBuf[1024];
intBufLen=1024;

//---------------------------------------------
//InitializeWinsock
WSAStartup(MAKEWORD(2,2),&wsaData);

//---------------------------------------------
//Createasocketforsendingdata
SendSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

//---------------------------------------------
//SetuptheRecvAddrstructurewiththeIPaddressof
//thereceiver(inthisexamplecase"123.456.789.1")
//andthespecifiedportnumber.
RecvAddr.sin_family=AF_INET;
RecvAddr.sin_port=htons(Port);
RecvAddr.sin_addr.s_addr=inet_addr("123.456.789.1");

//---------------------------------------------
//Sendadatagramtothereceiver
printf("Sendingadatagramtothereceiver...\n");
sendto(SendSocket,
SendBuf,
BufLen,
0,
(SOCKADDR*)&RecvAddr,
sizeof(RecvAddr));

//---------------------------------------------
//Whentheapplicationisfinishedsending,closethesocket.
printf("Finishedsending.Closingsocket.\n");
closesocket(SendSocket);

//---------------------------------------------
//Cleanupandquit.
printf("Exiting.\n");
WSACleanup();
return;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com