[Learning] Socket Initialization.
Last Update:
Word Count:
Read Time:
Introduction
This article introduces how to initialize socket in different programming languages, such as C++, C# and Python on both Linux and Windows.
What is socket?
A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programming interface (API) for the networking architecture. Sockets are created only during the lifetime of a process of an application running in the node.
Because of the standardization of the TCP/IP protocols in the development of the Internet, the term network socket is most commonly used in the context of the Internet protocol suite, and is therefore often also referred to as Internet socket. In this context, a socket is externally identified to other hosts by its socket address, which is the triad of transport protocol, IP address, and port number.
The term socket is also used for the software endpoint of node-internal inter-process communication (IPC), which often uses the same API as a network socket. —— Wikipedia
…Well, this might look confusing at first.
The simplest way to think about it is to imagine an abstract, invisible transmission line between two devices.
Device A connects to Device B and sends information.
This “invisible transmission line” is what we call a socket.
Devices establish stable communication through TCP sockets.
Establishment of socket
C++ (Linux)
Functions that you need to know:
- socket()
1
int socket(int domain, int type, int protocol);
- Domain: The working domain of your socket:
| Domain | Meaning |
|---|---|
| AF_INET | IPv4 internetwork(Device to device). |
| AF_INET6 | IPv4 internetwork(Device to device). |
| AF_UNIX | Unix(Process to process). |
- Type: The communication method:
| Type | Meaning |
|---|---|
| SOCK_STREAM | TCP communication |
| SOCK_DGRAM | UDP datagram. |
- Protocol: Protocol standard, usually set to 0.
socket() return 0 for successed establishment, otherwise -1.
- connect()
1
int connect(int sockfd, struct sockaddr_in *server, int addr_len);
- sockfd: The return value of socket()
- server: The information about this socket.
1
2
3
4
5
6
7
8
9
10struct sockaddr_in {
short sin_family; //AF_INET
unsigned short sin_port; //Port number.
struct in_addr sin_addr;
char sin_zero[8]; //Not used, must be zero.
}
struct in_addr {
unsigned long s_addr; //Load with inet_pton()
}
This function is used by the socket client.
bind()
1
int bind(int sockfd, struct sockaddr* addr, int addrlen);listen()
1
int listen(int sockfd, int backlog);
This function is used by the socket server.
Completed code
server.cpp1
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#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("socket");
return 1;
}
sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080); // Port
server_addr.sin_addr.s_addr = INADDR_ANY; // 0.0.0.0
if (bind(server_fd, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
close(server_fd);
return 1;
}
if (listen(server_fd, 5) < 0) {
perror("listen");
close(server_fd);
return 1;
}
std::cout << "Server listening on port 8080...\n";
sockaddr_in client_addr{};
socklen_t client_len = sizeof(client_addr);
int client_fd = accept(server_fd, (sockaddr*)&client_addr, &client_len);
if (client_fd < 0) {
perror("accept");
close(server_fd);
return 1;
}
char buffer[1024] = {0};
read(client_fd, buffer, sizeof(buffer));
std::cout << "Client says: " << buffer << std::endl;
const char* reply = "Hello from server";
send(client_fd, reply, strlen(reply), 0);
close(client_fd);
close(server_fd);
return 0;
}
client.cpp1
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#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
return 1;
}
sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (connect(sock, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("connect");
close(sock);
return 1;
}
const char* message = "Hello from client";
send(sock, message, strlen(message), 0);
char buffer[1024] = {0};
read(sock, buffer, sizeof(buffer));
std::cout << "Server reply: " << buffer << std::endl;
close(sock);
return 0;
}
Compile and execute:1
2
3
4
5
6$ g++ server.cpp -o server
$ g++ client.cpp -o client
$ ./server
$ ./client
C++ (Windows)
Different to Linux platform. We use WSA(Windows Sockets API)/Winsock on Windows platform.
Completed code
server.cpp1
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#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsa;
WSAStartup(MAKEWORD(2,2), &wsa);
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in serverAddr{};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
serverAddr.sin_addr.s_addr = INADDR_ANY;
bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
listen(serverSocket, 5);
std::cout << "Server listening on port 8080...\n";
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
char buffer[1024] = {};
recv(clientSocket, buffer, sizeof(buffer), 0);
std::cout << "Client: " << buffer << std::endl;
const char* msg = "Hello from Windows server";
send(clientSocket, msg, strlen(msg), 0);
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();
return 0;
}
client.cpp1
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#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsa;
WSAStartup(MAKEWORD(2,2), &wsa);
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in serverAddr{};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr);
connect(sock, (sockaddr*)&serverAddr, sizeof(serverAddr));
const char* msg = "Hello from Windows client";
send(sock, msg, strlen(msg), 0);
char buffer[1024] = {};
recv(sock, buffer, sizeof(buffer), 0);
std::cout << "Server: " << buffer << std::endl;
closesocket(sock);
WSACleanup();
return 0;
}
C
server.cs1
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
32using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Server
{
static void Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8080);
listener.Start();
Console.WriteLine("Server listening on port 8080...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected");
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Client says: " + message);
string reply = "Hello from C# server";
byte[] data = Encoding.UTF8.GetBytes(reply);
stream.Write(data, 0, data.Length);
client.Close();
listener.Stop();
}
}
client.cs1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26using System;
using System.Net.Sockets;
using System.Text;
class Client
{
static void Main()
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 8080);
NetworkStream stream = client.GetStream();
string message = "Hello from C# client";
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string reply = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Server reply: " + reply);
client.Close();
}
}
Python
server.py1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 8080))
server_socket.listen(5)
print("Server listening on port 8080...")
client_socket, client_addr = server_socket.accept()
print("Client connected:", client_addr)
data = client_socket.recv(1024)
print("Client says:", data.decode())
client_socket.send(b"Hello from Python server")
client_socket.close()
server_socket.close()
client.py1
2
3
4
5
6
7
8
9
10
11
12import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 8080))
client_socket.send(b"Hello from Python client")
data = client_socket.recv(1024)
print("Server reply:", data.decode())
client_socket.close()