The User Packet protocol ( User Datagram Protocal , UDP ) UDP requires only 1 sockets for both the server side and the client. TCPproviding services to 10 clients in, 10 server-side sockets are required in addition to the gatekeeper's server sockets.
UDPThe connection state is not saved, so the destination address information is added each time the data is transferred.
#include <sys/socket.h>ssize_t sendto(intvoidintstruct// 成功时返回传输的字节数,失败时返回-1~ sock: 用于传输数据的 UDP 套接字文件描述符~ buf: 待传输数据的缓冲地址值~ nbytes: 待传输数据的字节长度~ flag: 可选项参数,没有则传递0~ to: 目标地址的结构体变量地址~ addrlen: 地址结构体的长度
Receive function:
#include <sys/socket.h>ssize_t recvfrom(intvoidint flags,structfrom// 成功时返回接收的函数,失败时返回-1from: 存有发送端地址信息的结构体变量地址值
UDPEcho Server-side instance code based on
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define Buf_sizevoidErr_handling (Char*message);intMainintargcChar*argv[]) {intServ_sock;CharMessage[buf_size];intStr_len;structSockaddr_in Serv_adr;structSockaddr_in Clnt_adr; Socklen_t CLNT_ADR_SZ;if(ARGC! =2) {printf("Usage:%s <port> \ n", argv[0]);Exit(1); } Serv_sock = socket (pf_inet, SOCK_DGRAM,0);if(Serv_sock = =-1) Err_handling ("socket () error");memset(&serv_adr,0,sizeof(SERV_ADR)); serv_adr.sin_family = af_inet; SERV_ADR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Serv_adr.sin_port = htons (Atoi (argv[1]));if(Bind (Serv_sock, (structsockaddr*) &serv_adr,sizeof(SERV_ADR)) == -1) Err_handling ("Shenmecuoel bind () error"); while(1) {CLNT_ADR_SZ =sizeof(CLNT_ADR); Str_len = Recvfrom (serv_sock, message, Buf_size,0, (structsockaddr*) &clnt_adr, &CLNT_ADR_SZ); SendTo (serv_sock, message, Str_len,0, (structsockaddr*) &clnt_adr, CLNT_ADR_SZ); } close (Serv_sock);return 0;}voidErr_handling (Char* message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}
UDPEcho Client instance code based on
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define Buf_sizevoidError_handling (Char* message);intMainintargcChar*argv[]) {intSockCharMessage[buf_size];intStr_len; Socklen_t ADDR_SZ;structSockaddr_in serv_addr, from_addr;if(ARGC! =3) {printf("Usage:%s <IP> <port> \ n", argv[0]);Exit(1); } sock = socket (pf_inet, SOCK_DGRAM,0);if(Sock = =-1) Error_handling ("socket () error");memset(&SERV_ADDR,0,sizeof(SERV_ADDR)); serv_addr.sin_family = af_inet; SERV_ADDR.SIN_ADDR.S_ADDR = inet_addr (argv[1]); Serv_addr.sin_port = htons (Atoi (argv[2])); while(1) {fputs("Inputs message (Q to quit):", stdout); Fgets (Message,sizeof(message), stdin);if(!strcmp(Message,"q\n")) Break; SendTo (sock, message,strlen(message),0, (structsockaddr*) &serv_addr,sizeof(SERV_ADDR)); ADDR_SZ =sizeof(FROM_ADDR); Str_len = recvfrom (sock, message, Buf_size,0, (structsockaddr*) &from_addr, &ADDR_SZ); Message[str_len] =0;printf("Message from server:%s \ n", message); } close (sock);return 0;}voidError_handling (Char* message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}
is connectedUDPSockets and not connectedUDPSockets
The use is sendto divided into the following three stages:
UDPregistering targets IP and port numbers with sockets
- Transferring data
- Remove the target address information registered in the socket
The socket for this unregistered destination address information becomes an disconnected socket. The default is an unbound socket, but if the data is transferred multiple times to the consent target, this is clearly offset, and the first and third steps consume about One-third of the time.
To create a connected socket, you only need to call the function on the UDP socket connect .
0); 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; ...; ...; connect(sock, (struct sockaddr*)&addr, sizeof(addr));
UDPcalling connect a function on a socket does not mean connecting to the other UDP socket, which simply UDP registers the target information with the socket.
read write Information interaction can be achieved by registering information and then using and reading and writing related sockets.
Graceful disconnection (semi-shutdown of TCP)
Using shutdown functions to achieve semi-close
#include <sys/socket.h>int shutdown(intint// 成功时返回0,失败时返回-1~ sock: 需要断开的套接字文件描述符~ howto: 传递断开的方式 SHUT_RD(关闭度连接-流) SHUT_WR(关闭写连接-流) SHUT_REWD(关闭读写连接-流)
Domain name and network address get IP address using domain name
#include <netdb.h>struct hostent * gethostbyname(constchar//成功返回 hostent 结构体指针,失败返回 NULL 指针
struct hostent{ char// 官方域名,通常不使用 char// 同一主页的多个域名 int// 地址族信息,若是IPv4, 保存AF_INET int// IP 地址长度,4字节或是6字节 char// 同一域名的多个 IP 地址,通过数组保存, h_addr_list 保存数组的地址}
IPget domain name with address
#include <netdb.h>struct hostent * gethostbyaddr(constcharint// 同上~ addr: 含有IP地址信息的 in_addr 结构体指针~ len: 第一个参数的地址信息的字节数,4或6~ family: 地址族信息
Multiple options for sockets
#include <sys/socket.h> int getsockopt (int sock, int level, int optname, void *optval, socklen_t *optlen); //successfully returned 0, failed to return 1 ~ sock: the socket to view ~ level: Optional protocol layer to view ~ optname: Optional name to view ~ optval: Save View results Buffer Address Value ~ Optlen: Buffer Address size
#include <sys/socket.h>int setsockopt(intintintconstvoid// 同上
SO_SNDBUFis the output buffer size, which SO_RCVBUF is the input buffer size.
Understand the Time-Wait status, adjust the SO_REUSEADDR parameters ( TRUE set to) to Time-Wait reassign the socket port number in the state to the new socket.
Understand Negla the algorithm by TCP_NODELAY modifying the parameters.
TCP/IP network programming (ii)