mtp_dump.c 2.12 KB
Newer Older
Timothy Stack's avatar
 
Timothy Stack committed
1
2
3
4

#include "config.h"

#include <stdio.h>
Timothy Stack's avatar
Timothy Stack committed
5
#include <string.h>
Timothy Stack's avatar
 
Timothy Stack committed
6
7
8
9
10
11
12
13
14
15
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/socket.h>
David Johnson's avatar
David Johnson committed
16
#include <string.h>
Timothy Stack's avatar
 
Timothy Stack committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

#include "mtp.h"

static int mygethostbyname(struct sockaddr_in *host_addr, char *host)
{
    struct hostent *host_ent;
    int retval = 0;

    assert(host_addr != NULL);
    assert(host != NULL);
    assert(strlen(host) > 0);

    if( (host_ent = gethostbyname(host)) != NULL ) {
	memcpy((char *)&host_addr->sin_addr.s_addr,
	       host_ent->h_addr,
	       host_ent->h_length);
	retval = 1;
    }
    else {
	retval = inet_aton(host, &host_addr->sin_addr);
    }
    return( retval );
}

static void usage(void)
{
    fprintf(stderr, "Usage: mtp_dump <host> <port>\n");
}

int main(int argc, char *argv[])
{
    int port = 0, max_packets = 0, retval = EXIT_FAILURE;
    struct sockaddr_in sin;
    
    memset(&sin, 0, sizeof(sin));
    
    if (argc < 3) {
	fprintf(stderr, "error: not enough arguments\n");
	usage();
    }
    else if (sscanf(argv[2], "%d", &port) != 1) {
	fprintf(stderr, "error: port is not a number\n");
    }
    else if ((argc > 3) && sscanf(argv[3], "%d", &max_packets) != 1) {
	fprintf(stderr, "error: max packets argument is not a number\n");
    }
    else if (mygethostbyname(&sin, argv[1]) == 0) {
	fprintf(stderr, "error: unknown host %s\n", argv[1]);
    }
    else {
	int fd;
	
David Johnson's avatar
David Johnson committed
69
#ifndef linux
Timothy Stack's avatar
 
Timothy Stack committed
70
	sin.sin_len = sizeof(sin);
David Johnson's avatar
David Johnson committed
71
#endif
Timothy Stack's avatar
 
Timothy Stack committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);
	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
	    perror("socket");
	    retval = EXIT_FAILURE;
	}
	else if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
	    perror("connect");
	}
	else {
	    struct mtp_packet *mp;
	    int lpc = 0;
	    
	    while (((max_packets == 0) || (lpc < max_packets)) &&
		   (mtp_receive_packet(fd, &mp) == MTP_PP_SUCCESS)) {
		mtp_print_packet(stdout, mp);
		
		mtp_free_packet(mp);
		mp = NULL;

		lpc += 1;
	    }
	    
	    close(fd);
	    fd = -1;
	}

	retval = EXIT_SUCCESS;
    }
    
    return retval;
}