I need to simulate a TCP RST connection issue. For this purpose, I'd need to write a C Client that connects to a TCP Server and send a TCP RST connection. I have found this sample code but on the Server side I don't see any Connection Reset traced. I'm not a expert on C so I wonder if anything is missing to send a RST Socket.
Any help? Thanks
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // Replace with client IP
server_addr.sin_port = htons(8080); // Replace with client port
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) != 0) {
perror("Connection failed");
exit(EXIT_FAILURE);
}
// Close the socket without graceful termination to send RST
close(sock);
return 0;
}
Between socket()
& connect()
you need to set the linger option. If the linger option is set and you exit a reset is send. close()
usually starts an orderly shutdown with a “FIN” packet.
struct linger sl;
bzero(&sl, sizeof(sl));
sl.l_onoff = 1;
sl.l_linger = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &sl, sizeof(sl)) < 0)
perror("setsockopt");