-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.h
98 lines (78 loc) · 2.13 KB
/
socket.h
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
#ifndef _SOCKET_H
#define _SOCKET_H
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <string>
#include <arpa/inet.h>
#include <exception>
#include "constants.h"
using namespace std;
class socket {
private:
int sockfd;
struct sockaddr_in addr;
string host;
public:
socket(const int p, const string& h) : sockfd(-1), host(h) {
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(p);
}
socket(const string& h) : sockfd(-1), host(h) {
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
}
socket(const int p) : sockfd(-1) {
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(p);
}
socket() : sockfd(-1) {
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
}
socket(socket& sock) {
*this = sock;
}
~socket() {
if (is_valid())
::close(sockfd);
}
// Server initialization
bool socketEstablish();
bool socketBind();
bool socketListen() const;
bool socketAccept(socket& sock) const;
// Client initialization
bool connect();
// Data Transmission
bool send (const string& str) const;
bool send(char *block, int length) const;
int recv (string& str) const;
//void set_non_blocking (const bool b);
bool is_valid() const { return sockfd != -1; }
void setPort(int p) {
addr.sin_port = htons(p);
}
void close();
};
class SocketException : public exception {
private:
string userMessage; // Exception message
public:
SocketException(const string &message, bool inclSysMsg = false) throw ();
~SocketException() throw () {}
const char *what() const throw ();
};
#endif