Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
T
tp1-ProgDev-mertens-guilherme
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package Registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Mertens De Andrade Guilherme
tp1-ProgDev-mertens-guilherme
Commits
ad4b3164
Commit
ad4b3164
authored
5 months ago
by
Mertens De Andrade Guilherme
Browse files
Options
Downloads
Patches
Plain Diff
Server with socket
parent
b81c93cf
No related branches found
Branches containing commit
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
server_6.c
+62
-0
62 additions, 0 deletions
server_6.c
with
62 additions
and
0 deletions
server_6.c
0 → 100644
+
62
−
0
View file @
ad4b3164
#include
<iostream>
#include
<cstdlib>
#include
<cstring>
#include
<sys/socket.h>
#include
<netinet/in.h>
#include
<unistd.h>
#include
<ctime>
#define PORT 8080
int
main
()
{
int
server_fd
,
new_socket
;
struct
sockaddr_in
address
;
int
opt
=
1
;
int
addrlen
=
sizeof
(
address
);
srand
(
time
(
0
));
if
((
server_fd
=
socket
(
AF_INET
,
SOCK_STREAM
,
0
))
==
0
)
{
perror
(
"socket failed"
);
exit
(
EXIT_FAILURE
);
}
address
.
sin_family
=
AF_INET
;
// IPv4
address
.
sin_addr
.
s_addr
=
INADDR_ANY
;
address
.
sin_port
=
htons
(
PORT
);
if
(
bind
(
server_fd
,
(
struct
sockaddr
*
)
&
address
,
sizeof
(
address
))
<
0
)
{
perror
(
"bind failed"
);
close
(
server_fd
);
exit
(
EXIT_FAILURE
);
}
if
(
listen
(
server_fd
,
3
)
<
0
)
{
perror
(
"listen failed"
);
close
(
server_fd
);
exit
(
EXIT_FAILURE
);
}
std
::
cout
<<
"Server is listening on port "
<<
PORT
<<
std
::
endl
;
if
((
new_socket
=
accept
(
server_fd
,
(
struct
sockaddr
*
)
&
address
,
(
socklen_t
*
)
&
addrlen
))
<
0
)
{
perror
(
"accept failed"
);
close
(
server_fd
);
exit
(
EXIT_FAILURE
);
}
while
(
true
)
{
int
random_number
=
rand
()
%
100
;
if
(
write
(
new_socket
,
&
random_number
,
sizeof
(
random_number
))
==
-
1
)
{
perror
(
"write failed"
);
close
(
new_socket
);
close
(
server_fd
);
exit
(
EXIT_FAILURE
);
}
std
::
cout
<<
"Sent: "
<<
random_number
<<
std
::
endl
;
sleep
(
1
);
}
close
(
new_socket
);
close
(
server_fd
);
return
0
;
}
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment