tcp.cpp
2.06 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "tcp.h"
int createSocket()
{
int sockfd;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
cout << "Could not create socket" << endl;
exit(3);
}
return sockfd;
}
void connect(int s, uint16_t port, char *hostname, int timeout)
{
struct in_addr *addr_ptr;
struct hostent *hostPtr;
string add;
hostPtr = gethostbyname(hostname);
if(hostPtr == NULL)
{
cout << "Could not resolve hostname" << endl;
exit(3);
}
addr_ptr = (struct in_addr *)*hostPtr->h_addr_list;
add = inet_ntoa(*addr_ptr);
if(add == "")
{
cout << "Invalid address" << endl;
exit(3);
}
struct sockaddr_in newSockAddr;
newSockAddr.sin_family = AF_INET;
newSockAddr.sin_port = htons(port);
newSockAddr.sin_addr.s_addr = inet_addr(add.c_str());
if(connect(s, (struct sockaddr *)&newSockAddr, sizeof(struct sockaddr)) != 0)
{
cout << "Could not connect to " << hostname << " on port " << port << endl;
exit(3);
}
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0)
{
cout << "Error setting socket timeout" << endl;
exit(3);
}
fcntl(s, F_SETFL, O_NONBLOCK);
}
int sendMsg(int s, const char *msg, size_t msgLength)
{
int bytes, total = 0;
while(total != msgLength)
{
bytes = send(s,msg+total,msgLength-total,0);
if(bytes == -1)
{
cout << "TCP: Could not write to socket." << endl;
exit(3);
}
total += bytes;
}
return total;
}
int recvMsg(int s, char *msg, size_t msgLength)
{
int bytes, total = 0;
while(total != msgLength)
{
bytes = recv(s, msg+total, msgLength-total,0);
if ( bytes <= 0 )
{
if(errno == EWOULDBLOCK || errno == EAGAIN)
{
return 0;
}
cout << "TCP: Could not read from socket." << endl;
exit(3);
}
total += bytes;
}
return total;
}