简体   繁体   English

创建后将POSIX套接字的类型从UDP更改为TCP

[英]Change the type of a POSIX socket from UDP to TCP after creation

Is it possible to change the type of a socket from UDP to TCP after creation of said socket? 创建套接字后,是否可以将套接字的类型从UDP更改为TCP?

int sockfd_udp = socket(AF_INET, SOCK_DGRAM, 0);

Depending on additional informations i want to switch the created socket sockfd_udp from UDP to TCP. 根据其他信息,我想将创建的套接字sockfd_udp从UDP切换到TCP。 I am aware that this is not intended to be done, but i'm searching a way to work around this problem. 我知道这不是要完成的,但我正在寻找解决此问题的方法。

It is also an option to create a new socket ( sockfd_tcp ) and close the old one ( sockfd_udp ), but in this case the new socket is required to have the same file descriptor as the old socket ( sockfd_tcp = sockfd_udp ). 这也是创建一个新的插座(选项sockfd_tcp ),并关闭旧的( sockfd_udp ),但在这种情况下,新的插座必须具有相同的文件描述符作为旧插座( sockfd_tcp = sockfd_udp )。

Try the following: 请尝试以下操作:

int sockfd_udp = socket(AF_INET, SOCK_DGRAM, 0);
...
int sockfd_tcp = socket(AF_INET, SOCK_STREAM, 0);
dup2(sockfd_tcp, sockfd_udp);
close(sockfd_tcp);
sockfd_tcp = sockfd_udp;

dup2() will close the UDP socket if it is still open. 如果dup2()仍然打开,它将关闭UDP套接字。 After the call the underlying TCP socket have two file descriptors: sockfd_tcp and sockfd_udp. 调用之后,基础TCP套接字具有两个文件描述符:sockfd_tcp和sockfd_udp。 Keep the wanted one, and close the other. 保留想要的一个,然后关闭另一个。

Add needed error checking, because those calls may fail. 添加所需的错误检查,因为这些调用可能会失败。

See man page of dup for more information. 有关更多信息,请参见dup的手册页

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM