-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
50 lines (35 loc) · 1.59 KB
/
client.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
/*
client.c
Joe O'Regan
16/02/2018
UDP client sends and receives messages from server
Default port 8888
*/
#include "socket.h" // Includes, definitions, functions, and variables common to both client and server
int main(int argc, char *argv[]) {
int sock, numbytes; // Socket, number of bytes sent/received
struct sockaddr_in srvAddr, inAddr; // Address structures
struct hostent *hp;
char buf[BUFLEN]; // String buffer
if (argc < 1 || argc > 3) {
errorEx("Usage: server port [Optional]\n", 1);
}
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) error("socket"); // Create the socket
srvAddr.sin_family = AF_INET;
hp = gethostbyname((argc >= 2) ? argv[1] : SERV_ADDR); // If an IP address is entered (parameter 2) use that, otherwise use default value
if (hp == 0) error("Unidentified host");
bcopy((char *)hp->h_addr, (char *)&srvAddr.sin_addr, hp->h_length);
srvAddr.sin_port = htons((argc == 3) ? atoi(argv[2]) : UDP_PORT); // If a port number is entered (parameter 3) use that, otherwise use default value
while (1) {
printf("Enter Message: ");
bzero(buf, BUFLEN); // Clear the buffer
fgets(buf, BUFLEN-1, stdin); // Get input from keyboard
if ((numbytes = sendto(sock, buf, strlen(buf),0,(const struct sockaddr*) &srvAddr, ADDR_SIZE)) < 0)
error("sendto()");
if ((numbytes = recvfrom(sock,buf,BUFLEN,0,(struct sockaddr *) &inAddr, &ADDR_SIZE)) < 0)
error("recvfrom()");
printf("Server %s:%u Replied: %s",inet_ntoa(inAddr.sin_addr), ntohs(inAddr.sin_port), buf); // print received message
}
close(sock);
return 0;
}