-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.cpp
More file actions
57 lines (47 loc) · 1.28 KB
/
socket.cpp
File metadata and controls
57 lines (47 loc) · 1.28 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
#include "Server.hpp"
using std::cout;
using std::endl;
SOCKET createSocket()
{
SOCKET socketFD = socket(AF_INET, SOCK_STREAM, 0);
int optVal = 1;
int optValSize = sizeof(optVal);
if (setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, (const char*)&optVal, optValSize) == -1
|| setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, (const char*)&optVal, optValSize) == -1)
throw socketCreationFailed();
fcntl(socketFD, F_SETFL, O_NONBLOCK);
if (socketFD == -1)
throw socketCreationFailed();
cout << "Socket created with fd: " << socketFD << endl;
return (socketFD);
}
int bindSocket(SOCKET socketFD, int port)
{
int bindRet;
sockaddr_in myAddr;
myAddr.sin_family = AF_INET;
myAddr.sin_port = htons(port);
inet_pton(AF_INET, "0.0.0.0", &myAddr.sin_addr);
bindRet = bind(socketFD, (sockaddr *)&myAddr, sizeof(myAddr));
if (bindRet == -1)
throw bindingSocketFailed();
cout << "Bind was successful!" << endl;
return (bindRet);
}
int listenOnSocket(SOCKET socketFD)
{
int listenRet;
listenRet = listen(socketFD, 128);
if (listenRet == -1)
throw listenOnSocketFailed();
cout << "Listen was successful!" << endl;
return (listenRet);
}
int setupSocket(int port)
{
SOCKET socketFD;
socketFD = createSocket();
bindSocket(socketFD, port);
listenOnSocket(socketFD);
return (socketFD);
}