如何使用UDP段中的数据建立TCP连接?

时间:2012-02-12 20:38:13

标签: c++ sockets tcp udp

我收到了来自UDP套接字fd的数据。如何使用此信息建立发件人的TCP连接。 buf包含TCP端口。

struct sockaddr_storage remote_addr;
socklen_t remote_addr_len;

recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remote_addr, &remote_addr_len);

下面的代码是我的尝试,但它不起作用。我是套接字编程的新手,我正在试图解决这个问题,我正在撕扯我的头发。

newfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *info;
info = gethostbyname(remoteAddr.h_addr);

struct sockaddr_in newConn;
newConn.sin_family = AF_INET;
bcopy((char *)info->h_addr, (char *)&newConn.sin_addr.s_addr, info->h_length);
newConn.sin_port = htons(mesgTcpPort); //mesgTcpPort is of type int gotten from buf


connect(newfd,(struct sockaddr *)&newConn,sizeof newConn);

省略错误检查。

1 个答案:

答案 0 :(得分:0)

您不应该需要gethostbyname,因为UDP数据包在其标题中包含IP地址,而不是名称(由recvfrom提供给您)。

但是,这种方法的适用性有限,因为新连接不会遍历NAT,因为它不会与原始UDP连接相关联,因为协议和端口不同。

相关问题