-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudp-cl.cpp
80 lines (64 loc) · 1.84 KB
/
udp-cl.cpp
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
// Credits:
// https://www.geeksforgeeks.org/udp-server-client-implementation-c/
// g++ udp-cl.cpp -o udp-cl
// Client side implementation of UDP client-server model
#include <bits/stdc++.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
// IP:Port for the server.
const char *ServerIPString = "192.168.1.4";
#define PORT 11888
#define MAXLINE 1024
// Driver code
int main(void)
{
int sockfd;
char buffer[MAXLINE];
const char *hello = "Hello from client";
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
//servaddr.sin_addr.s_addr = INADDR_ANY;
//servaddr.sin_addr.s_addr = inet_addr("192.168.1.4");
servaddr.sin_addr.s_addr = inet_addr(ServerIPString);
int n=0;
socklen_t len;
sendto(
sockfd,
(const char *)hello, strlen(hello),
MSG_CONFIRM,
(const struct sockaddr *) &servaddr,
sizeof(servaddr) );
std::cout << "Hello message sent." << std::endl;
/*
// #test: Waiting for response.
while (1)
{
n = recvfrom(
sockfd,
(char *) buffer,
MAXLINE,
MSG_WAITALL,
(struct sockaddr *) &servaddr,
&len );
if (n>0)
std::cout << "MESSAGE: " << buffer << std::endl;
};
*/
buffer[n] = '\0';
std::cout<<"Server :"<<buffer<<std::endl;
close(sockfd);
return 0;
}