Reputation: 673
I am coding a small nmap-like program, and actually, I create a socket for every packet I hand craft. Even if it send tcp packets, I don't want to have any tcp session ( I sniff responses and don't care about what happens after ). Should I only declare only one socket and reuse it for each packets.
Is this thread-safe to reuse a socket ?
Thanks.
int send_raw_packet(s_raw *data, size_t data_size)
{
struct sockaddr_in sin = { .sin_addr.s_addr = 1 };
int socket_fd;
int sendto_res = -1;
char interface[IFNAMSIZ] = "enp0s3"; // Trying things there
socket_fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, interface, ft_strlen(interface)) == -1)
perror("setsockopt: ");
if (socket_fd == -1)
{
perror("Socket: ");
}
else
{
sendto_res = sendto(socket_fd, data, data_size, 0, (struct sockaddr *)&sin, sizeof sin);
if (sendto_res == -1)
perror("\033[091msendto :\033[0m");
close(socket_fd);
}
return sendto_res;
}
Upvotes: 0
Views: 398
Reputation: 18420
Yes, you can reuse the socket over several threads or even several processes. The kernel makes sure, that concurrent access to the socket is handled properly.
However, you have to keep in mind that changing socket options will affect all processes and threads, which use this socket. Furthermore, packets arriving on the socket can only be read by one thread/process, they are not duplicated.
Upvotes: 1