-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudp_advance.cpp
127 lines (95 loc) · 2.33 KB
/
udp_advance.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
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
117
118
119
120
121
122
123
124
125
126
127
/* Advance UDP Server */
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <sys/wait.h>
#include <cstdlib>
#include <string>
#include <vector>
#include <cpuid.h>
#include <syslog.h>
#include <sys/uio.h>
#include <sys/event.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <pthread.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_dl.h>
#include <net/route.h>
using namespace std;
struct hdr{
int seq;
struct sockaddr_in sa;
};
int retransmit(struct sockaddr_in sa,int sockfd, struct hdr h){
int n;
struct msghdr msg = {};
struct iovec iov[1];
memset(&h.sa,0, sizeof(h.sa));
iov[0].iov_base = &h;
iov[0].iov_len = sizeof(struct hdr);
msg.msg_name = &sa;
msg.msg_namelen = sizeof(sa);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
n = sendmsg(sockfd,&msg,0);
if(n == -1){
perror("server - sendmsg");
return 0;
}
cout << "Message Retransmitted" << endl;
return 0;
}
int recv_msg(int sockfd){
int n;
// struct msghdr msg = {};
struct iovec iov[2];
char recv_buf[100];
struct hdr h;
iov[0].iov_base = &h;
iov[0].iov_len = sizeof(h);
iov[1].iov_base = recv_buf;
iov[1].iov_len = sizeof(recv_buf);
struct msghdr msg = {NULL,0,iov,2,0,0,0};
cout << "Listening for messages...." << endl;
n = recvmsg(sockfd,&msg,0);
if(n == -1){
perror("server - recvmsg");
return(1);
}
cout << "Message : " << recv_buf << endl;
cout << "Retransmitting the seq no" << endl;
retransmit(h.sa,sockfd,h);
}
int create_server(){
int sockfd;
struct sockaddr_in servaddr, cliaddr;
int n;
int port = 3456;
memset(&servaddr,0,sizeof(servaddr));
sockfd = socket(AF_INET,SOCK_DGRAM,0);
servaddr.sin_addr.s_addr =inet_addr("<your_ip_address>");
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if(bind(sockfd,(struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
perror("bind");
}
recv_msg(sockfd);
return 0;
}
int main(){
int x = create_server();
return 0;
}