|
| 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