Skip to content

Commit 856f3a4

Browse files
author
Your Name
committed
tcp raw socket, mkdir simple_examples
1 parent d7d426c commit 856f3a4

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

getaddrinfo.c renamed to simple_examples/getaddrinfo.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ int main(int argc, char **argv)
1212
struct addrinfo hints, *result, *tmp;
1313
struct sockaddr_in *sock_addr;
1414
int res;
15-
hints.ai_flags = AI_PASSIVE;
15+
hints.ai_flags = 0;
1616
hints.ai_family = AF_INET;
17-
hints.ai_socktype = SOCK_STREAM;
17+
hints.ai_socktype = SOCK_RAW;
1818
hints.ai_protocol = 0;
1919
hints.ai_addrlen = 0;
2020
hints.ai_canonname = NULL;

simple_examples/tcp.c

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <unistd.h>
4+
5+
#include <netdb.h>
6+
#include <sys/socket.h>
7+
#include <arpa/inet.h>
8+
9+
#include <netinet/in.h>
10+
#include <netinet/tcp.h>
11+
12+
int main(int argc, char *argv[])
13+
{
14+
struct addrinfo *hints, *answ, *tmp;
15+
struct tcphdr *send_frame;
16+
int sock, ret;
17+
ssize_t send_cnt;
18+
if (argc < 2) {
19+
fprintf(stderr, "need host name\n");
20+
exit(1);
21+
}
22+
if ( (hints = calloc(1, sizeof(struct addrinfo))) == NULL) {
23+
perror("calloc");
24+
exit(1);
25+
}
26+
if ( (send_frame = calloc(1, sizeof(struct tcphdr))) == NULL) {
27+
perror("malloc");
28+
exit(1);
29+
}
30+
hints->ai_family = AF_INET;
31+
hints->ai_socktype = SOCK_RAW;
32+
hints->ai_protocol = IPPROTO_TCP;
33+
if ( (ret = getaddrinfo(argv[1], NULL, hints, &answ)) != 0) {
34+
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret));
35+
exit(1);
36+
}
37+
for (tmp = answ; tmp != NULL; tmp = tmp->ai_next) {
38+
if ( (sock = socket(tmp->ai_family, tmp->ai_socktype,
39+
tmp->ai_protocol)) == -1) {
40+
perror("socket");
41+
if (tmp == NULL) { /*walk around the whole list*/
42+
fprintf(stderr, "failed open socket\n");
43+
exit(1);
44+
} else {
45+
continue;
46+
}
47+
} else {
48+
printf("was openned sock with addr: %s\n",
49+
inet_ntoa(((struct sockaddr_in *)tmp->
50+
ai_addr)->sin_addr) );
51+
break;
52+
}
53+
}
54+
/*old method:
55+
if ( (sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1) {
56+
perror("socket");
57+
exit(1);
58+
}
59+
*/
60+
send_cnt = sendto(sock, send_frame, sizeof(struct tcphdr), 0,
61+
tmp->ai_addr, tmp->ai_addrlen);
62+
if (send_cnt == -1) {
63+
perror("sendto");
64+
exit(1);
65+
}
66+
return 0;
67+
}

0 commit comments

Comments
 (0)