/
linux_tcp_server_ipv4.cpp
116 lines (103 loc) · 2.7 KB
/
linux_tcp_server_ipv4.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
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
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
using namespace std;
int main(int argc, char const *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// setsockopt(sockfd, 0, O_NONBLOCK, 0, 0);
if (sockfd < 0)
{
perror("ERROR Opening socket.");
exit(1);
}
else
{
cout << "Opened socket!\n";
}
bzero((char *)&serv_addr, sizeof(serv_addr));
portno = 1234; // Port number goes here.
// Configure server details.
serv_addr.sin_family = AF_INET; // More details on types: man socket
serv_addr.sin_addr.s_addr = INADDR_ANY; // Allow any interface.
serv_addr.sin_port = htons(portno);
cout << "Port: " << portno << "\n"; // Output the port number, you could also ask for a custom port and use that.
// Start binding the socket.
if (
bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR binding.");
exit(1);
}
else
{
cout << "Binded socket!\n";
}
// Nap until it gets an incomming connection.
if (listen(sockfd, 5) < 0)
{
perror("ERROR Listening to the socket");
}
else
{
// change 5 to how ever many connections you want in queue before refusing to connect
cout << "Now listening to the socket!\n";
clilen
= sizeof(cli_addr); // 16 is default, change this to how ever many (or little) you want!
cout << "Number of connections allowed in queue before refusing to connect: " << clilen
<< "\n";
}
while(1)
{
// Accept the connection from client
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newsockfd < 0)
{
perror("ERROR Socket accept");
exit(1);
}
else
{
cout << "Accepted connection!\n";
}
// Connected established, let's start communicating
bzero(buffer, 256);
n = read(newsockfd, buffer, 255);
if (n < 0)
{
perror("ERROR Reading from socket!\n");
exit(1);
}
else
{
cout << "Connection estabilished!\n";
}
printf("Recieved message: \n%s\n", buffer);
// Send something back to client!
n = write(newsockfd, "PONG", 18);
if (n < 0)
{
perror("ERROR writing to socket failed.");
exit(1);
}
else
{
cout << "Sent PONG message!\n";
}
}
// Close socket
close(sockfd);
close(newsockfd);
return 0;
};