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.