当前位置:编程学习 > C/C++ >>

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

追问:能否再给发个基于tcp的呢?还有 本机指定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;
}

套接字

上一个:学编程如何入门?C++最好用吗?
下一个:我想学编程C++,高手指导下好点自学的方法.

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,