-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSocket.cpp
executable file
·46 lines (37 loc) · 1.18 KB
/
CSocket.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
#include "CSocket.h"
#include <iostream>
CSocket::CSocket(unsigned short destPort, const char* destIP, unsigned short srcPort, const char* srcIP){
#if _WIN32
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("WSAStartup failed.\n");
return;
}
#endif
to_addr.sin_family = AF_INET;
to_addr.sin_port = htons(destPort);
to_addr.sin_addr.s_addr = (destIP == NULL) ? 0 : inet_addr(destIP);
to_me.sin_family = AF_INET;
to_me.sin_port = htons(srcPort);
to_me.sin_addr.s_addr = (srcIP == NULL) ? 0 : inet_addr(srcIP);
if ((nSocket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("talker: socket");
}
if ( bind( nSocket, (sockaddr*)&to_me, sizeof( to_me ) ) == -1)
{
printf("Error binding/n");
return;
}
}
int CSocket::Send(void* msg, int count){
auto nSockAdrSize = sizeof(sockaddr_in);
auto nSendCount = sendto(nSocket, (char*)msg, count, 0, (struct sockaddr*)&to_addr, nSockAdrSize);
return nSendCount;
}
int CSocket::Read(void* buf, int maxCount){
int nTempSockAdrSize = sizeof(sockaddr_in);
auto nReadCount = recv(nSocket, (char*)buf, maxCount, 0);
return nReadCount;
}