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

如题所述

首先你要确定要用什么协议来传送 TCP 还是 UDP 给你发个基于UDP协议的吧#include <stdio.h>
#include "winsock2.h"

void main() {

WSADATA wsaData;
SOCKET SendSocket;
sockaddr_in RecvAddr;
int Port = 27015;
char SendBuf[1024];
int BufLen = 1024;

//---------------------------------------------
// Initialize Winsock
WSAStartup(MAKEWORD(2,2), &wsaData);

//---------------------------------------------
// Create a socket for sending data
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

//---------------------------------------------
// Set up the RecvAddr structure with the IP address of
// the receiver (in this example case "123.456.789.1")
// and the specified port number.
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = inet_addr("123.456.789.1");

//---------------------------------------------
// Send a datagram to the receiver
printf("Sending a datagram to the receiver...\n");
sendto(SendSocket,
SendBuf,
BufLen,
0,
(SOCKADDR *) &RecvAddr,
sizeof(RecvAddr));

//---------------------------------------------
// When the application is finished sending, close the socket.
printf("Finished sending. Closing socket.\n");
closesocket(SendSocket);

//---------------------------------------------
// Clean up and quit.
printf("Exiting.\n");
WSACleanup();
return;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-07-06
套接字
相似回答