当前位置:网站首页>Socket programming (Part 1)
Socket programming (Part 1)
2022-06-13 11:09:00 【Think and act 66】
socket Programming ( On )
List of articles
1. Five tuple information of network data
- Source ip Address : Identify the host from which network data is sent
- Source port : Identify the source of network data ip Which process of the corresponding host generates
- Purpose ip: Indicates which host the network data will go to
- Destination port : Through purpose ip After finding the destination host , Find the corresponding process through the destination port
- agreement : When both parties transmit data , What protocol to use ( It's usually TCP/IP)
2. Network byte order
We already know , Multi byte data in memory can be divided into large end and small end relative to memory address , The multi byte data in the disk file is relative to the offset in the file
Moving addresses can also be divided into large and small ends , Network data flow can also be divided into large end and small end . So how to define the address of network data flow ?
- Small endian byte order : Put the low address in the low address
- Big endian byte order : Put the low address in the high address
- Host byte order : It refers to the byte order of the machine itself , If it's big end , Then the host byte order is big end . If it's small end , Then the host byte order is small end
- Network byte order : It is specified that when the network transmits data, the big end byte order is used for transmission
Conversion between host byte order and network byte order
Convert host byte order to network byte order
ip:unint32_t
uint32_t htonl(uint32_t hostlong);
port:uint16_t
uint16_t htons(uint16_t hostshort);
Convert network byte order to host byte order
ip:unint32_t
uint32_t ntohl(uint32_t hostlong);
port:uint16_t
uint16_t ntohs(uint16_t hostshort);
3.TCP/UDP Protocol characteristics and differences
UDP:
- There is no connection :UDP Both parties do not need to communicate before sending data , Just need to know each other's ip And port can be sent
- unreliable : No guarantee UDP Data is reliable 、 Arrive at each other in an orderly way
- For datagram :UDP And application layer / When the network layer submits data, the whole data is delivered
TCP:
- Connection oriented :TCP A connection will be established before sending data (1. Ensure that the other party can communicate normally .2. Communicate details of subsequent data sent by both parties ( For example, serial number ))
- Reliable transmission :TCP Ensure that the transmitted data is reliable 、 Arrive at the opposite end orderly
- Byte stream oriented :1. There is no transmission boundary for the transmitted data
2. For the recipient , May, in accordance with the 1 Receive any byte
4.UDP-socket Programming
technological process :
Server side : Create socket , Binding address information
client : Create socket , Binding address information is not recommended ( Can be bound )
Why create sockets ?
Bind the process to the network card , The process can receive data from the network card , You can also send data through the network card
Why bind address information ?
binding ip, Binding ports is to identify a host and a process in the network
For the recipient , The sender will know which host and which process the receiver is in
For the sender , It can identify which machine and which process the network data is sent from
5. Programming interface (API)
Create socket :
#include<sys/socket.h>
int socket(int domain,int type,int protocol);
- domain: Address field - Select a specific protocol family for communication ,TCP/UDP, You can think of what protocol to use at the specified network layer
AF_UNIX: Local domain socket ( Use files to communicate on the same machine , No cross machine )
AF_INET:ipv4 Version of ip agreement
AF_INET6:ipv Version of IP agreement- type: The type of socket
SOCK_DGRAM: User datagram socket - Corresponding UDP
SOCK_STREAM: Streaming socket - Corresponding TCP- protocol: agreement
0: Indicates that the default protocol is selected according to the socket type
Specific agreements can also be implemented :
IPPROTO_TCP(6): representative TCP agreement
IPPROTO_UDP(17): representative UDP agreement- Return value : Return socket operation handle , It is essentially a file descriptor
Greater than or equal to 0: Create success
Less than 0: Create failure
Binding interface :
int bind(int sockfd,const struct sockaddr *addr,socklen_t addrlen);
- sockfd: socket descriptor
- addr: Bound address information
- addrlen: Length of bound address information
Send interface :
ssize_t sendto(int sockfd,const void *buf,size_t len,int flags,const struct sockaddr *deat_addr,socklen_t addrlen);
- sockfd: socket descriptor
- buf: Data to send
- len: The length of data to be sent
- flags:0( Blocking transmission )
- dest_addr: Address information structure , Contains the purpose ip, Destination port
- addrlen: Length of address information
- Return value : success , Return the data sent normally ; Failure , return -1
Receiving interface :
ssize_t resvfrom(int sockfd,void *buf,size_t len,int flags,struct sockaddr *src_addr,socklen_t *addrlen);
- sockfd: socket descriptor
- buf: A buffer prepared by a programmer to receive data
- len: Maximum acceptable data size
- flags:0( Blocking reception )
- src_addr: Source ip+ Source port
- addrlen: This is a reference , Return the length of the address information
General data structure :
struct sockaddr{
sa_family_t sa_family;// Address field , Takes two bytes
char sa_data[14];
};
struct sockaddr_in{
sa_family_t sin_family;// Address family
uint16_t sin_port;// Port number
struct in_addr sin_addr;//32 position IP Address
char sin_zero[8];// Reserved unused
};
struct in_addr{
In_addr_t s_addr;//32 position IPV4 Address
};
Code :
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main(){
//1. Create socket
int sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sockfd<0){
perror("socket");
return 0;
}
printf("sockfd is %d\n",sockfd);
//2. Binding address information
struct sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_port=htons(28989);
//1. Will be dotted decimal ip Convert to unsigned 32 An integer
//2. The unsigned 32 Bit integer to network byte order
addr.sin_addr.s_addr=inet_addr("10.0.16.3");
int ret=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
if(ret<0){
perror("bind");
return 0;
}
while(1){
sleep(1);
}
return 0;
}
边栏推荐
猜你喜欢

Brief description of redo logs and undo logs in MySQL

There is no suspense about the first one in the overtime table of the Internet company!

Meta universe land: what makes digital real estate valuable

Do you agree that the salary of hardware engineers is falsely high?

【TcaplusDB知识库】Tmonitor系统升级介绍

Experience of electric competition - program-controlled wind pendulum

Redis相关

Euler function and finding Euler function by linear sieve

Folder data synchronization tool sync folders Pro

关于 SAP Spartacus CmsService.getComponentData 可能的优化思路
随机推荐
State compression DP example (traveling salesman problem and rectangle filling problem)
很妙的贪心(F2. Nearest Beautiful Number (hard version))
vivo大规模 Kubernetes 集群自动化运维实践
Web 3.0?高成本版的P2P而已
【TcaplusDB知识库】Tmonitor单机安装指引介绍(一)
D generate unique ID at compile time
D evaluate twice map
ACP | 东北地理所在气象-空气质量双向耦合模式研究中取得进展
2021CCPC网络赛题解加总结
MFC自定义button实现颜色控制
Prim求最小生成树(朴素版稠密图)
程序员面试这么重视考察概念还是第一次见
ue5 小知识点 geometry script modeling
Finally, the monthly income is 20000!!
Actual combat analysis of malicious code lab05-01
Prim finding minimum spanning tree (naive dense graph)
Nim游戏阶梯 Nim游戏和SG函数应用(集合游戏)
Digital DP example
Performance monster on arm64: installation and performance test of API gateway Apache APIs IX on AWS graviton3
区间修改乘和加(理解懒标记的好例题)