C++ Tutorial Sockets - Server & Client - 2020
C++ Tutorial Sockets - Server & Client - 2020
Thank you.
PRICE DROP
- K Hong (http://bogotobogo.com/about_us.php)
1 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
C++ Tutorials
C++ Home (/cplusplus/cpptut.php)
auto_ptr (/cplusplus/autoptr.php)
1. A client app send a request to a server app. Boost - shared_ptr, weak_ptr, mpl,
2. The server app returns a reply. lambda, etc. (/cplusplus/boost.php)
3. Some of the basic data communications between client and server are:
1. File transfer - sends name and gets a �le. Boost.Asio (Socket Programming -
2. Web page - sends url and gets a page. Asynchronous TCP/IP)... (/cplusplus
/Boost
3. Echo - sends a message and gets it back.
/boost_AsynchIO_asio_tcpip_socket_server
2 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
/embeddedSystemsProgramming_gnu_too
Exceptions (/cplusplus
/exceptions.php)
1. Boost.Asio - 1. Blocking and non-blocking wait with timers (http://www.bogotobogo.com/cplusplus/Boost Functors (Function Objects) II -
/boost_AsynchIO_asio_tcpip_socket_server_client_timer_A.php) Converting function to functor
2. Boost.Asio - 2. Binding arguments to a callback handler member function (http://www.bogotobogo.com (/cplusplus
/cplusplus/Boost/boost_AsynchIO_asio_tcpip_socket_server_client_timer_bind_handler_member_function_B.php) /functor_function_object_stl_2.php)
3. Boost.Asio - 3. Multithreading, synchronizing, and handler (http://www.bogotobogo.com/cplusplus/Boost
Functors (Function Objects) -
/boost_AsynchIO_asio_tcpip_socket_server_client_timer_bind_handler_multithreading_synchronizing_C.php)
General (/cplusplus/functors.php)
4. Boost.Asio - 4. TCP Socket Programming (http://www.bogotobogo.com/cplusplus/Boost
/boost_AsynchIO_asio_tcpip_socket_server_client_timer_bind_handler_multithreading_synchronizing_network_D.php)
For socket programming with Qt, please visit Git and GitHub Express... (/cplusplus
http://www.bogotobogo.com/cplusplus/sockets_server_client_QT.php (/cplusplus/sockets_server_client_QT.php). /Git/Git_GitHub_Express.php)
Multi-Threaded Programming -
Terminology - Semaphore, Mutex,
Priority Inversion etc. (/cplusplus
/multithreaded.php)
3 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
Multi-Threaded Programming II -
Native Thread for Win32 (A)
(/cplusplus
Socket - summary /multithreading_win32A.php)
Here is the summary of key concepts:
Multi-Threaded Programming II -
1. Socket is a way of speaking to other programs using standard . Native Thread for Win32 (B)
(/cplusplus
2. Where do we get the �le descriptor for network communication?
/multithreading_win32B.php)
Well, we make a call to the system routine.
After the socket() returns the socket descriptor, we start communicate through it using the specialized
Multi-Threaded Programming II -
socket API calls. Native Thread for Win32 (C)
3. A TCP socket is an (/cplusplus
4. A TCP socket is , it is the of a speci�c connection. /multithreading_win32C.php)
5. A TCP is de�ned by aka sockets.
6. The purpose of is to on a given network address. Multi-Threaded Programming II -
7. The port numbers are encoded in the transport protocol packet header, and they can be readily interpreted not C++ Thread for Win32 (/cplusplus
/multithreading_win32.php)
only by the sending and receiving computers, but also by other components of the networking infrastructure. In
particular, �rewalls are commonly con�gured to di�erentiate between packets based on their source or
Multi-Threaded Programming III -
destination as in . C/C++ Class Thread for Pthreads
8. It is the (the consisting of the client IP address, client port number, server IP address, and (/cplusplus
server port number) that speci�es the two endpoints that uniquely identi�es each in an /multithreading_pthread.php)
internet.
9. Only may bind to a speci�c and combination using the . MultiThreading/Parallel
Otherwise, we'll have , where multiple programs attempt to bind to the same port numbers on the Programming - IPC (/cplusplus
/multithreading_ipc.php)
same IP address using the same protocol.
A between two machines, where . Those two pieces of Multi-Threaded Programming with
software know how to communicate with each other. In other words, they know how to send to each other. C++11 Part B (Sharing Data - mutex,
A socket connection means the two machines have information about each other, including and race conditions, and deadlock)
and . (If we can use anology, IP address is the and the TCP port is the ). (/cplusplus
A socket is an object similar to a �le that allows a program to accept incoming connections, make outgoing /multithreaded4_cplusplus11B.php)
A socket is a assigned to the server process. The server creates it using the system call , and it can't Object Returning (/cplusplus
be shared with other processes. /object_returning.php)
Pointers (/cplusplus/pointers.php)
4 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
/pointers2_voidpointers_arrays.php)
Arbitrary length content Limited message size Standard Template Library (STL) II -
Flow control matches sender to receiver Can send regardless of receiver state
Sets (/cplusplus/stl2B_set.php)
Congestion control matches sender to network Can send regardless of network state
Standard Template Library (STL) III -
tftp (trivial �le transfer protocol), dhcpcd (a DHCP client), Iterators (/cplusplus
multiplayer games, streaming audio, video conferencing /stl3_iterators.php)
http, telnet
*note: They use complementary protocol on top of UDP to get
Standard Template Library (STL) IV -
more reliability
Algorithms (/cplusplus
/stl4_algorithms.php)
1.
Stream sockets provide communication similar to when we call someone on the phone. One Standard Template Library (STL) V -
side initiates the connection to the other, and after the connection is established, either side can communicate Function Objects (/cplusplus
to the other. /stl5_function_objects.php)
In addition, there is immediate con�rmation that what we said actually reached its destination.
Stream sockets use a , which exists on the transport layer of the Open Static Variables and Static Class
Members (/cplusplus/statics.php)
Systems Interconnection (OSI) model. The data is usually transmitted in packets. TCP is designed so that the
5 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
6 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
2. The server process gives the socket a name. In linux �le system, local sockets are given a �lename, under /tmp or
/usr/tmp directory. For network sockets, the �lename will be a service identi�er, port number, to which the
clients can make connection. This identi�er allows to route incoming connections (which has that the port Qt 5 EXPRESS...
number) to connect server process. A socket is named using system call. (/Qt/Qt5_Creating_QtQuick2_QML_Applica
3. The server process then waits for a client to connect to the named socket, which is basically listening for
connections with the system call. If there are more than one client are trying to make connections, the Win32 DLL ... (/Win32API
system call make a queue. /Win32API_DLL.php)
The machine receiving the connection (the server) must bind its socket object to a known port number. A port is
Articles On C++ (/cplusplus
a 16-bit number in the range 0-65535 that's managed by the operating system and used by clients to uniquely
/cppNews.php)
identify servers. Ports 0-1023 are reserved by the system and used by common network protocols.
4. Accept a connection with the system call. At , a new socket is created that is distinct from the What's new in C++11... (/cplusplus
named socket. This new socket is used solely for communication with this particular client. /C11/C11_initializer_list.php)
For TCP servers, the socket object used to receive connections is not the same socket used to perform
subsequent communication with the client. In particular, the system call returns a new socket object C++11 Threads EXPRESS...
that's actually used for the connection. This allows a server to manage connections from a large number of (/cplusplus
clients simultaneously. /C11/1_C11_creating_thread.php)
5. Send and receive data.
Go Tutorial (/GoLang
6. The named socket remains for further connections from other clients. A typical web server can take advantage of
/GoLang_Closures_Anonymous_Functions.
multiple connections. In other words, it can serve pages to many clients at once. But for a simple server, further
clients wait on the listen queue until the server is ready again. OpenCV... (/OpenCV
/opencv_3_tutorial_imgproc_gausian_med
The steps to establish a socket on the side are:
7 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
Socket Functions
, in C, behaves like �les because they use �le descriptors to identify themselves. Sockets behave so much like
�les that we can use the and to receive and send data using .
There are several functions, however, speci�cally designed to handle sockets. These functions have their prototypes
de�ned in .
1.
8 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
Used to create a new socket, returns a �le descriptor for the socket or -1 on error.
It takes three parameters:
The parameters allow us to say what kind of socket we want (IPv4/IPv6, stream/datagram(TCP/UDP)).
1. The protocol family should be or
2. and the protocol type for these two families is
either for TCP/IP or for UDP/IP.
3. The protocol should usually be set to zero to indicate that the default protocol should be used.
2.
Once we have a socket, we might have to associate that socket with a port on our local machine.
The port number is used by the kernel to match an incoming packet to a certain process's socket descriptor.
A server will call with the address of the local host and the port on which it will listen for connections.
It takes �le descriptor (previously established socket), a pointer to (the address of) a structure containing the
details of the address to bind to, the value is typically used for this, and the length of the address
structure.
The particular structure that needs to be used will depend on the protocol, which is why it is passed by the
pointer.
So, this call will bind the socket to the current IP address on port, portno
Returns 0 on success and -1 on error.
3.
Once a server has been bound to an address, the server can then call on the socket.
The parameters to this call are the socket (fd) and the maximum number of queued connections requests up to
.
Returns 0 on success and -1 on error.
4.
Accepts an incoming connection on a bound socket. The address information from the remote host is written
into the structure and the actual size of the address structure is written into .
In other words, this function will write the connecting client's address info into the address structure.
Then, returns a new socket �le descriptor for the accepted connection.
So, the original socket �le descriptor can continue to be used for accepting new connections while the new
socket �le descriptor is used for communicating with the connected client.
This function returns a new socket �le descriptor to identify the connected socket or -1 on error.
If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept()
blocks the caller until a connection is present.
5.
This is a blocking call. That's because when we issue a call to connect(), our program doesn't regain control until
either the connection is made, or an error occurs. For example, let's say that we're writing a web browser. We try
9 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
to connect to a web server, but the server isn't responding. So, we now want the connect() API to stop trying to
connect by clicking a stop button. But that can't be done. It waits for a return which could be 0 on success or -1
on error.
6.
7.
This is another blocking call. In other words, when we call to read from a stream, control isn't returned to
our program until at least one byte of data is read from the remote site. This process of waiting for data to
appear is referred to as . The same is true for the write() and the connect() APIs, etc. When we run those
blocking APIs, the connection "blocks" until the operation is complete.
The following server code listens for TCP connections on port 20001. When a client connects, it sends the message
"Hello world!", and then it receives data from client.
10 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
portno = atoi(argv[1]);
// convert short integer value for port must be converted into network byte order
serv_addr.sin_port = htons(portno);
// This listen() call tells the socket to listen to the incoming connections.
// The listen() function places all incoming connection into a backlog queue
// until accept() call accepts the connection.
// Here, we set the maximum size for the backlog queue to 5.
listen(sockfd,5);
// This accept() function will write the connecting client's address info
// into the the address structure and the size of that structure is clilen.
// The accept() returns a new socket file descriptor for the accepted connection.
// So, the original socket file descriptor can continue to be used
// for accepting new connections while the new socker file descriptor is used for
// communicating with the connected client.
newsockfd = accept(sockfd,
(struct sockaddr *) &cli;_addr, &clilen;);
if (newsockfd < 0)
error("ERROR on accept");
11 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
// This send() function sends the 13 bytes of the string to the new socket
send(newsockfd, "Hello, world!\n", 13, 0);
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
close(newsockfd);
close(sockfd);
return 0;
}
When a socket is created with the function, the , , and of the socket must be speci�ed.
The domain refers to the protocol family of the socket.
/* Address families. */
#define AF_UNSPEC PF_UNSPEC
#define AF_LOCAL PF_LOCAL
#define AF_UNIX PF_UNIX
#define AF_FILE PF_FILE
#define AF_INET PF_INET
#define AF_AX25 PF_AX25
#define AF_IPX PF_IPX
#define AF_APPLETALK PF_APPLETALK
#define AF_NETROM PF_NETROM
#define AF_BRIDGE PF_BRIDGE
#define AF_ATMPVC PF_ATMPVC
#define AF_X25 PF_X25
#define AF_INET6 PF_INET6
#define AF_ROSE PF_ROSE
#define AF_DECnet PF_DECnet
#define AF_NETBEUI PF_NETBEUI
#define AF_SECURITY PF_SECURITY
#define AF_KEY PF_KEY
#define AF_NETLINK PF_NETLINK
#define AF_ROUTE PF_ROUTE
#define AF_PACKET PF_PACKET
#define AF_ASH PF_ASH
#define AF_ECONET PF_ECONET
#define AF_ATMSVC PF_ATMSVC
#define AF_SNA PF_SNA
#define AF_IRDA PF_IRDA
#define AF_PPPOX PF_PPPOX
#define AF_WANPIPE PF_WANPIPE
#define AF_BLUETOOTH PF_BLUETOOTH
#define AF_MAX PF_MAX
A socket can be used to communicate using a variety of protocols, from the standard Internet protocol used when we
browse the Web. These families are de�ned in , which is automatically included from .
There are several types of sockets: stream sockets and datagram sockets are the most commonly used. The types of
sockets are also de�ned in
12 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
/* Types of sockets. */
enum __socket_type
{
SOCK_STREAM = 1, /* Sequenced, reliable, connection-based
byte streams. */
#define SOCK_STREAM SOCK_STREAM
SOCK_DGRAM = 2, /* Connectionless, unreliable datagrams
of fixed maximum length. */
#define SOCK_DGRAM SOCK_DGRAM
SOCK_RAW = 3, /* Raw protocol interface. */
#define SOCK_RAW SOCK_RAW
SOCK_RDM = 4, /* Reliably-delivered messages. */
#define SOCK_RDM SOCK_RDM
SOCK_SEQPACKET = 5, /* Sequenced, reliable, connection-based,
datagrams of fixed maximum length. */
#define SOCK_SEQPACKET SOCK_SEQPACKET
SOCK_PACKET = 10 /* Linux specific way of getting packets
at the dev level. For writing rarp and
other similar things on the user level. */
#define SOCK_PACKET SOCK_PACKET
};
The 3rd argument for the function is the protocol, which should always be 0. The speci�cation allows for
multiple protocols within a protocol family, so this argument is used to select on of the protocols from the family.
/* Protocol families. */
#define PF_UNSPEC 0 /* Unspecified. */
#define PF_LOCAL 1 /* Local to host (pipes and file-domain). */
#define PF_UNIX PF_LOCAL /* Old BSD name for PF_LOCAL. */
#define PF_FILE PF_LOCAL /* Another non-standard name for PF_LOCAL. */
#define PF_INET 2 /* IP protocol family. */
#define PF_AX25 3 /* Amateur Radio AX.25. */
#define PF_IPX 4 /* Novell Internet Protocol. */
#define PF_APPLETALK 5 /* Appletalk DDP. */
#define PF_NETROM 6 /* Amateur radio NetROM. */
#define PF_BRIDGE 7 /* Multiprotocol bridge. */
#define PF_ATMPVC 8 /* ATM PVCs. */
#define PF_X25 9 /* Reserved for X.25 project. */
#define PF_INET6 10 /* IP version 6. */
#define PF_ROSE 11 /* Amateur Radio X.25 PLP. */
#define PF_DECnet 12 /* Reserved for DECnet project. */
#define PF_NETBEUI 13 /* Reserved for 802.2LLC project. */
#define PF_SECURITY 14 /* Security callback pseudo AF. */
#define PF_KEY 15 /* PF_KEY key management API. */
#define PF_NETLINK 16
#define PF_ROUTE PF_NETLINK /* Alias to emulate 4.4BSD. */
#define PF_PACKET 17 /* Packet family. */
#define PF_ASH 18 /* Ash. */
#define PF_ECONET 19 /* Acorn Econet. */
#define PF_ATMSVC 20 /* ATM SVCs. */
#define PF_SNA 22 /* Linux SNA Project */
#define PF_IRDA 23 /* IRDA sockets. */
#define PF_PPPOX 24 /* PPPoX sockets. */
#define PF_WANPIPE 25 /* Wanpipe API sockets. */
However, in practice, most protocol families only have one protocol, which means this should usually be set for 0; the
�rst and only protocol in the enumeration of the family.
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
13 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
The lines above set up the structure for use in the call.
The address family is , since we are using and the structure. The short integer value for
port must be converted into network byte order, so the (Host-to-Network Short) function is used.
The call passes the socket �le descriptor, the address structure, and the length of the address structure. This
call will bind the socket to the current IP address on port 20001.
The call tells the socket to listen for incoming connections, and a subsequent call actually accepts an
incoming connection. The function places all incoming connections into a backlog queue until an call
accepts the connections. The last argument to the call sets the maximum size for the backlog queue.
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli;_addr, &clilen;);
if (newsockfd < 0) error("ERROR on accept");
The �nal argument of the is a pointer to the size of the address structure. This is because the
function will write the connecting client's address information into the address structure and the size of that structure
is . The function returns a new socket �le descriptor for the accepted connection:
newsockfd = accept(sockfd,
(struct sockaddr *) &cli;_addr,&clilen;);
This way, the original socket �le descriptor can continue to be used for accepting new connections, while the new
socket �le descriptor is used for communicating with the connected client.
The function sends the 13 bytes of the string to the new socket that describes the new
connection.
and to run
./server port#
14 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv;_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv;_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv;_addr, sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd, buffer, 255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n", buffer);
close(sockfd);
return 0;
}
To compile
and to run
First, we run as in
15 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
$ ./server 20001
Then, on
$ ./server 20001
server: got connection from 127.0.0.1 port 47173
Then, on
$ ./server 20001
server: got connection from 127.0.0.1 port 47173
Here is the message: Hello from Client
CONTACT
BogoToBogo
[email protected] (mailto:[email protected])
FOLLOW BOGOTOBOGO
(https://www.facebook.com/KHongSanFrancisco) (https://twitter.com/KHongTwit)
ABOUT US (/ABOUT_US.PHP)
[email protected] (mailto:[email protected])
16 of 17 23/09/22, 07:55
C++ Tutorial: Sockets - Server & Client - 2020 https://www.bogotobogo.com/cplusplus/sockets_server...
17 of 17 23/09/22, 07:55