-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket_utils.h
More file actions
105 lines (90 loc) · 2.1 KB
/
socket_utils.h
File metadata and controls
105 lines (90 loc) · 2.1 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#ifndef _SOCKET_UTILS_H
#define _SOCKET_UTILS_H
//
// Copyright (c) 2002 by Ted T. Yuan.
//
// Permission is granted to use this code without restriction as long as this copyright notice appears in all source files.
//
#if defined(WIN32)
#include <windows.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <resolv.h>
#include <netdb.h>
#endif
/////////////////////////////////////
// Win32 specific
#if defined(WIN32)
inline void initializeWinsock()
{
// must init the winsock first
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2,2);
if(0 != WSAStartup(wVersionRequested, &wsaData))
{
perror("Winsock initialization failed");
exit(1);
}
}
inline void closeWinsock()
{
WSACleanup();
}
#else
inline void initializeWinsock() {}
inline void closeWinsock() {}
#endif
inline int createServerSocket(short sourcePort, int backlog)
{
int sd;
struct sockaddr_in sin;
// get an internet domain socket
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("ssocket");
return -1;
}
// complete the socket structure
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(sourcePort);
// bind the socket to the port number
if (bind(sd, (struct sockaddr *) &sin, sizeof(sin)) == -1) {
perror("bind");
return -1;
}
// show that we are willing to listen
if (listen(sd, backlog) == -1) {
perror("listen");
return -1;
}
return sd;
}
inline int acceptClientSocket(int server, struct sockaddr_in& pin)
{
int client;
#if defined(WIN32)
int addrlen = sizeof(struct sockaddr_in);
#else
size_t addrlen = sizeof(struct sockaddr_in);
#endif
if ((client = accept(server, (struct sockaddr *) &pin, &addrlen)) == -1) {
perror("accept");
#if defined(WIN32)
//wprintf (L"Socket accept, error %d\n", WSAGetLastError ());
#endif
}
return client;
}
inline void CloseConnection(int server) // socket id
{
#if defined(WIN32)
closesocket(server);
#else
close(server);
#endif
}
#endif