mtp_recv.c 1.8 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

#include "mtp.h"

int main(int argc, char *argv[])
{
    int fd, port = 0, retval = EXIT_SUCCESS;

    if ((argc == 2) && sscanf(argv[1], "%d", &port) != 1) {
	fprintf(stderr, "error: port argument is not a number: %s\n", argv[1]);
	retval = EXIT_FAILURE;
    }
    else if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
	perror("socket");
	retval = EXIT_FAILURE;
    }
    else {
	struct sockaddr_in sin;
	int on_off = 1;
	
	memset(&sin, 0, sizeof(sin));
David Johnson's avatar
David Johnson committed
37
#ifndef linux
Timothy Stack's avatar
 
Timothy Stack committed
38
	sin.sin_len = sizeof(sin);
David Johnson's avatar
David Johnson committed
39
#endif
Timothy Stack's avatar
 
Timothy Stack committed
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
69
70
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);
	sin.sin_addr.s_addr = INADDR_ANY;

	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on_off, sizeof(int));
	
	if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
	    perror("bind");
	    retval = EXIT_FAILURE;
	}
	else if (listen(fd, 5) == -1) {
	    perror("listen");
	    retval = EXIT_FAILURE;
	}
	else {
	    struct sockaddr_in sin_peer;
	    socklen_t slen;
	    int fd_peer;

	    slen = sizeof(sin_peer);
	    
	    getsockname(fd, (struct sockaddr *)&sin, &slen);
	    printf("Listening for mtp packets on port: %d\n",
		   ntohs(sin.sin_port));
	    
	    while ((fd_peer = accept(fd,
				     (struct sockaddr *)&sin_peer,
				     &slen)) != -1) {
		struct mtp_packet *mp;
		
		while (mtp_receive_packet(fd_peer, &mp) == MTP_PP_SUCCESS) {
Timothy Stack's avatar
   
Timothy Stack committed
71
		    mtp_print_packet(stdout, mp);
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
		    
		    mtp_free_packet(mp);
		    mp = NULL;
		}

		close(fd_peer);
		fd_peer = -1;
		
		slen = sizeof(sin_peer);
	    }
	    
	    perror("accept");
	}
	
	close(fd);
	fd = -1;
    }
    
    return retval;
}