-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient_FileIO_UDP.c
More file actions
79 lines (63 loc) · 1.59 KB
/
Client_FileIO_UDP.c
File metadata and controls
79 lines (63 loc) · 1.59 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
if (argc < 3)
{ // using command line argument
printf("Usage: %s <serv_ip> <serv_port>\n", argv[0]);
exit(1);
}
int cfd, serv_port;
serv_port = strtoul(argv[2], NULL, 10);//string to unsigned long
/*
Create your Socket do error checking
Remember socket returns a socket descriptor
SOCK_STREAM --->TCP
or
SOCK_DGRAM --->UDP
AF_INET ------->protocol/address family
*/
if ((cfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(2);
}
struct sockaddr_in saddr = {0};
saddr.sin_family = AF_INET; // set to AF_INET
saddr.sin_port = htons(serv_port); // Port number
saddr.sin_addr.s_addr = inet_addr(argv[1]); // IP address eg "192.168.1.1"
/*
1. Connect to the server using proper API for connect
2. Send data to connected server
3. Receive data from connected server and print data received
4. Close the connection
*/
if (connect(cfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
{
perror("connect");
close(cfd);
exit(3);
}
FILE *fpc = NULL;
char buf[100], ch;
char cptr[2] = {0};
int ccount = 0,nbytes = 0;
fpc = fopen("samplec.txt", "r");
if(fpc == NULL){
perror("fopen");
exit(5);
}
nbytes = fread(buf, 1, 100, fpc);
socklen_t len = sizeof(saddr);
if (sendto(cfd, buf, nbytes, 0, (struct sockaddr *)&saddr, len) < 0) {
perror("sendto");
close(cfd);
exit(4);
}
close(cfd);
return 0;
}