Portál AbcLinuxu, 24. října 2025 08:29
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 80 /* the port client will be connecting to */
#define MAXDATASIZE 100 /* max number of bytes we can get at once */
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr; /* connector's address information */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(5557);
my_addr.sin_addr.s_addr = inet_addr("192.168.1.42");
bzero(&(my_addr.sin_zero), 8); /* zero the rest of the struct */
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("BIND ERROR");
exit(1);
}
their_addr.sin_family = AF_INET; /* host byte order */
their_addr.sin_port = htons(PORT); /* short, network byte order */
their_addr.sin_addr.s_addr = inet_addr("1.2.3.4");
bzero(&(their_addr.sin_zero), 8); /* zero the rest of the struct */
if (connect(sockfd, (struct sockaddr *)&their_addr, \
sizeof(struct sockaddr)) == -1) {
perror("connect");
exit(1);
}
sleep(5);
char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault
return 0;
}
TCP v AF_INET/SOCK_STREAM spravuje jadro, a to zajisti, ze i po nespravnem ukonceni procesu dojde ke spravnemu ukonceni TCP spojeni skrze signalizaci RST a FIN (a spoustu dalsich veci). Pokud toto chcete udelat z userspace (tzn. z uzivatelskeho procesu), tak musite pouzit raw sockety ... ale to znamena take vytvaret 'plnohodnotne' IP packety a mit rootovska prava (ci ekvivalent).
https://www.systutorials.com/docs/linux/man/7-raw/
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.