-
Notifications
You must be signed in to change notification settings - Fork 0
/
udpplay.c
116 lines (100 loc) · 2.04 KB
/
udpplay.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
69
70
71
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
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
abest: cheap udp packet
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PACKET (0xffff - 29)
#define BUFSIZE 1024
int main(int argc, char *argv[])
{
int sock, r;
int z;
int len;
int port = 12345;
struct sockaddr_in sAddr;
struct sockaddr_in cAddr;
struct hostent *he;
char *buf;
int buflen = 0;
char *p;
//ARGS
if (argc < 2)
{
fprintf(stderr, "%s <host> <port>\n", argv[0]);
exit(1);
}
port = atoi(argv[2]);
he = gethostbyname(argv[1]);
if (he == NULL)
{
fprintf(stderr, "%s: Unable to resolve host '%s' \n", argv[0], argv[1]);
exit(1);
}
sAddr.sin_family = he->h_addrtype;
memcpy((char *) &sAddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
sAddr.sin_port = htons(port);
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (0 > sock)
{
fprintf(stderr, "%s: unable to open socket\n", argv[0]);
exit(1);
}
cAddr.sin_family = AF_INET;
cAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cAddr.sin_port = htons(0);
if (0 > bind(sock, (struct sockaddr *) &cAddr, sizeof(cAddr)))
{
fprintf(stderr, "%s: unable to bind socket\n", argv[0]);
exit(1);
}
// Not exactly the best method.
len = 0;
p = buf = malloc(sizeof(char) * BUFSIZE);
buflen = BUFSIZE;
if (!buf)
{
fprintf(stderr, "%s: malloc failed\n", argv[0]);
exit(1);
}
do
{
if (len == buflen)
{
buf = (char *) realloc(buf, (sizeof(char) * buflen) + (sizeof(char) * BUFSIZE));
if (!buf)
{
fprintf(stderr, "%s: Realloc failed\n", argv[0]);
exit(1);
}
p = buf;
p += len;
buflen += BUFSIZE;
}
z = fread(p, sizeof(char), buflen - len, stdin);
if (z > 0)
{
len += z;
p += z;
}
}
while (z > 0);
/*
fwrite(buf, len, sizeof(char), stdout);
return 1;
*/
r = sendto(sock, buf, len, 0, (struct sockaddr *) &sAddr, sizeof(sAddr));
if (0 > r)
{
fprintf(stderr, "r = %i\n", r);
fprintf(stderr, "%s: unable to write to socket\n", argv[0]);
exit(1);
}
return 0;
}