当前位置:网站首页>C language: explain in detail the two local communication methods based on TCP and UDP
C language: explain in detail the two local communication methods based on TCP and UDP
2022-07-24 01:00:00 【lhb2998658795】
One . Local communication (UNIX Domain socket )
1.1 Concept
socket It can also be used for local communication to create sockets using local protocols PF_UNIX( or PF_LOCAL) It is divided into streaming socket and user datagram socket , The difference is whether there is a connection or not, which is often used for front and back process communication .
The mechanism used
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* Path and file name */
};1.2TCP Local communication process
The server :
Create socket socket( )
Populate the server local information structure sockaddr_un
Bind the socket to the server local information structure bind( )
Set the socket to passive listening state listen( )
Block the connection request waiting for the client accept( )
communicate recv( )/send( ) or read( )/write( )
client :
Create socket socket( )
Populate the server local information structure sockaddr_un
Send the connection request of the client connect( )
communicate send( )/recv( )
1.3 Code implementation
Code instructions : This is a code for a cyclic response , To explain local communication
Server code
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(2 != argc){
printf("Usage : %s <filename>\n", argv[0]);
return -1;
}
// Create a streaming socket
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Fill information local information structure
struct sockaddr_un serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sun_family = AF_UNIX;
strcpy(serveraddr.sun_path, argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// binding
if(-1 == bind(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("bind error");
}
// monitor
if(-1 == listen(sockfd, 5)){
ERRLOG("listen error");
}
// Define the structure to save the information of the other party
struct sockaddr_un clientaddr;
memset(&clientaddr, 0, sizeof(clientaddr));
socklen_t clientaddr_len = sizeof(clientaddr);
int acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientaddr_len);
if(-1 == acceptfd){
ERRLOG("accept error");
}
printf(" client [%s] Connect to the server \n", clientaddr.sun_path);
char buff[128] = {0};
while(1){
if(-1 == recv(acceptfd, buff, 128, 0)){
ERRLOG("recv error");
}
printf(" client [%s] Send data [%s]\n", clientaddr.sun_path, buff);
strcat(buff, "--hqyj");
if(-1 == send(acceptfd, buff, 128, 0)){
ERRLOG("send error");
}
memset(buff, 0, 128);
}
close(acceptfd);
close(sockfd);
return 0;
}client
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(2 != argc){
printf("Usage : %s <filename>\n", argv[0]);
return -1;
}
// Create a streaming socket
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Populate the server local information structure
struct sockaddr_un serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sun_family = AF_UNIX;
strcpy(serveraddr.sun_path, argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// Define the client local information structure
struct sockaddr_un clientaddr;
memset(&clientaddr, 0, sizeof(clientaddr));
clientaddr.sun_family = AF_UNIX;
strcpy(clientaddr.sun_path,"tcp_client_file");
socklen_t clientaddr_len = sizeof(clientaddr);
// Client needs binding , Otherwise, the server cannot receive the file name of the client
if(-1 == bind(sockfd, (struct sockaddr *)&clientaddr, clientaddr_len)){
ERRLOG("bind error");
}
if(-1 == connect(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("accept error");
}
printf(" Successfully connected to the server \n");
char buff[128] = {0};
while(1){
fgets(buff, 128, stdin);
buff[strlen(buff)-1] = '\0';
if(-1 == send(sockfd, buff, 128, 0)){
ERRLOG("send error");
}
if(-1 == recv(sockfd, buff, 128, 0)){
ERRLOG("recv error");
}
printf(" The reply [%s]\n", buff);
memset(buff, 0, 128);
}
close(sockfd);
return 0;
}Two UDP Local communication
2.1 technological process
The server :
Create socket socket( )
Populate the server local information structure sockaddr_un
Bind the socket to the server local information structure bind( )
communicate recvfrom( ) / sendto( )
client :
Create socket socket( )
Fill in the client local information structure sockaddr_un
Bind the socket to the client local information structure bind()
Populate the server local information structure sockaddr_un
communicate sendto( ) / recvfrom( )
2.2 Code implementation
The server
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(2 != argc){
printf("Usage : %s <filename>\n", argv[0]);
return -1;
}
// Create user datagram socket
int sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Fill in the local information structure of server information
struct sockaddr_un serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sun_family = AF_UNIX;
strcpy(serveraddr.sun_path, argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// binding
if(-1 == bind(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("bind error");
}
// Define the structure to save the information of the other party
struct sockaddr_un clientaddr;
memset(&clientaddr, 0, sizeof(clientaddr));
socklen_t clientaddr_len = sizeof(clientaddr);
char buff[128] = {0};
while(1){
if(-1 == recvfrom(sockfd, buff, 128, 0, (struct sockaddr *)&clientaddr, &clientaddr_len)){
ERRLOG("recv error");
}
printf(" client [%s] Send data [%s]\n", clientaddr.sun_path, buff);
strcat(buff, "--hqyj");
if(-1 == sendto(sockfd, buff, 128, 0, (struct sockaddr *)&clientaddr, clientaddr_len)){
ERRLOG("send error");
}
memset(buff, 0, 128);
}
close(sockfd);
return 0;
}client
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(3 != argc){
printf("Usage : %s <server_filename> <client_filename>\n", argv[0]);
return -1;
}
// Create user datagram socket
int sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Populate the server local information structure
struct sockaddr_un serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sun_family = AF_UNIX;
strcpy(serveraddr.sun_path, argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// Define the client local information structure
struct sockaddr_un clientaddr;
memset(&clientaddr, 0, sizeof(clientaddr));
clientaddr.sun_family = AF_UNIX;
strcpy(clientaddr.sun_path, argv[2]);
socklen_t clientaddr_len = sizeof(clientaddr);
// Client needs binding , Otherwise, the server cannot receive the file name of the client
if(-1 == bind(sockfd, (struct sockaddr *)&clientaddr, clientaddr_len)){
ERRLOG("bind error");
}
char buff[128] = {0};
while(1){
fgets(buff, 128, stdin);
buff[strlen(buff)-1] = '\0';
if(-1 == sendto(sockfd, buff, 128, 0, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("send error");
}
// because serveraddr No change. So there is no need to save
if(-1 == recvfrom(sockfd, buff, 128, 0, NULL, NULL)){
ERRLOG("recv error");
}
printf(" The reply [%s]\n", buff);
memset(buff, 0, 128);
}
close(sockfd);
return 0;
}边栏推荐
- 1000 okaleido tiger launched binance NFT, triggering a rush to buy
- Solve the problem that MySQL inserts Chinese garbled code into the table
- 工作3年的测试员跳槽后工资是原来的2倍,秘诀原来是......
- Design details related to sap e-commerce cloud Spartacus UI store
- Database connection pool & dbutils
- Tutorial on the principle and application of database system (046) -- MySQL query (VIII): group by
- Installation and use of appscan
- [QNX Hypervisor 2.2用户手册]9 VM配置参考
- 黑马程序员-接口测试-四天学习接口测试-第四天-Postman读取外部数据文件,读取数据文件数据,iHRM项目实战,员工管理模块,添加员工,批量运行测试用例,生成测试报告,
- Basic use of crawler requests module
猜你喜欢

How to relieve the pillow quickly

Solve the problem that MySQL inserts Chinese garbled code into the table

Basic exercises of C language for beginners

Hcia-01 initial understanding of the Internet

黑马程序员-接口测试-四天学习接口测试-第四天-Postman读取外部数据文件,读取数据文件数据,iHRM项目实战,员工管理模块,添加员工,批量运行测试用例,生成测试报告,
For data security reasons, the Dutch Ministry of Education asked schools to suspend the use of Chrome browser

The way to access global variables in multi-source file mode (extern usage)

Analysis of the advantages of the LAAS scheme of elephant swap led to strong performance of ETOKEN

【LeetCode第 83 场双周赛】

Installation and use of appscan
随机推荐
The winverifytrust call returned 80096005 error. The timestamp signature or certificate cannot be verified or is damaged
MySQL common commands
mysql 分支语句case报错
docker mysql
Installation and use of appscan
PostgreSQL snapshot optimization globalvis new system analysis (greatly enhanced performance)
QT入门篇(2.1初入QT的开始第一个程序)
Bean Validation使用篇----05
Prometheus+node exporter+grafana monitoring server system resources
Tutorial on principles and applications of database system (047) -- MySQL query (IX): connection query
Bean Validation自定义容器验证篇----06
The high-quality digital collection of guochuang's "children's song line" is on sale, and you are invited to create a young martial arts Jianghu dream
Use of crawler request library 2
About redis: there is still a risk of data loss after redis sets data persistence
【複盤】關於我在錯誤的時間選錯了技術這件事
Image processing: Generation 3 × Window of 3
[the 83rd fortnight of leetcode]
Educational Codeforces Round 132 (Rated for Div. 2) D. Rorororobot
[STM32] basic knowledge of serial communication
落枕如何快速缓解