forked from CSS-D/Net-Task2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.cpp
More file actions
68 lines (63 loc) · 2.44 KB
/
Copy pathSocket.cpp
File metadata and controls
68 lines (63 loc) · 2.44 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
#include "Socket.h"
void WSA_initialization()
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2, 2), &wsadata)) //version 2.2
{
cout << "initialization failed " << endl;
}
}
SOCKET create_recv_socket()
{
SOCKET recv_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (recv_socket == INVALID_SOCKET)
{
cout << "socket fail" << endl;
exit(1);
}
sockaddr_in local_addr;
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(RECV_PORT);
local_addr.sin_addr.S_un.S_addr = INADDR_ANY;
bind(recv_socket, (sockaddr *)&local_addr, sizeof(local_addr));
return recv_socket;
}
SOCKET create_send_socket()
{
return socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
void send_message(SOCKET socket, long dest_ip_addr, u_short dest_port, Message message)
{
struct sockaddr_in toAddr;
toAddr.sin_family = AF_INET;
toAddr.sin_port = htons(dest_port);
toAddr.sin_addr.s_addr = dest_ip_addr;
int flag = sendto(socket, (char *)&message, sizeof(message), 0, (SOCKADDR *)&toAddr, sizeof(toAddr));
cout << "\n[send to " << inet_ntoa(*((in_addr *)&dest_ip_addr)) << "]\t";
cout << "type: " << message.message_type << "\t";
cout << "source ip: " << inet_ntoa(*((in_addr *)&message.source_ip_addr)) << "\t";
cout << "dest ip: " << inet_ntoa(*((in_addr *)&message.dest_ip_addr)) << "\t";
cout << "cost: " << message.cost << endl;
if (flag == SOCKET_ERROR)
printf("Message send failed!\nError:\n%d\n", WSAGetLastError());
}
Message recv_message(SOCKET recv_socket, long &from_ip_addr)
{
Message message;
memset(&message, 0, sizeof(message));
char buffer[BUFFER_SIZE];
memset(buffer, 0, sizeof(buffer));
struct sockaddr_in from_addr;
int addr_size = sizeof(from_addr);
int flag = recvfrom(recv_socket, buffer, BUFFER_SIZE, 0, (SOCKADDR *)&from_addr, &addr_size);
if (flag == SOCKET_ERROR)
printf("Message recv failed!\nError:\n%d\n", WSAGetLastError());
memcpy((char *)&message, (const char *)buffer, sizeof(message));
from_ip_addr = from_addr.sin_addr.S_un.S_addr;
cout << "\n[recv from " << inet_ntoa(*((in_addr *)&from_ip_addr)) << "]\t";
cout << "type: " << message.message_type << "\t";
cout << "source ip: " << inet_ntoa(*((in_addr *)&message.source_ip_addr)) << "\t";
cout << "dest ip: " << inet_ntoa(*((in_addr *)&message.dest_ip_addr)) << "\t";
cout << "cost: " << message.cost << endl;
return message;
}