简体   繁体   中英

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?

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. 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 ).

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. After the call the underlying TCP socket have two file descriptors: sockfd_tcp and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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