- Socket
- Socket function
- TCP Code implementation
- UDP Code Implementation
Socket
First introduce the socket start-up process:
Depending on how the connection is started and the destination to which the local socket is connected, the connection between sockets can be divided into three steps: Server listening, client request, connection acknowledgement.
(1) Server monitoring: Is the server end socket does not locate the specific client socket, but in the status of waiting for the connection, real-time monitoring network status.
(2) Client request: Refers to the client's socket to make a connection request, to connect to the target is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
(3) Connection confirmation: When the server-side socket is heard or received a client socket connection request, it responds to the client socket request, set up a new thread, the server-side socket description to the client, once the client confirms the description, the connection is established. While the server-side socket continues to be in the listening state, it continues to receive connection requests from other client sockets. Content from Baidu
Socket function
Create
Function Prototypes:
int socket(int domain, int type, int protocol);
- Domain: The Protocol field, also known as the Protocol Family (family). Common protocol families are af_inet, Af_inet6, af_local (or Af_unix,unix domain sockets), Af_route, and so on. The protocol family determines the socket address type, must use the corresponding address in the communication, such as Af_inet decided to use the IPv4 address (32 bits) and the port number (16 bit) combination, Af_unix decided to use an absolute path name as the address.
- Type: Specifies the socket type. Common socket types are sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket, and so on. A streaming socket (SOCK_STREAM) is a connection-oriented socket for connection-oriented TCP service applications. A datagram Socket (SOCK_DGRAM) is a non-connected socket that corresponds to a non-connected UDP service application.
- Protocol: Specifies the protocol. Common protocols are ipproto_tcp, IPPROTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, respectively, corresponding to TCP transmission protocol, UDP Transmission protocol, STCP Transmission protocol, TIPC transmission protocol.
If the call succeeds, the descriptor of the newly created socket is returned, and if the failure returns Invalid_socket (Linux fails back-1).
Binding
Function prototypes
int bind(SOCKET socket, const struct sockaddr* address, socklen_t address_len);
- Socket: is a socket descriptor.
- Address: is a SOCKADDR structure pointer that contains the address and port number to be combined.
- Address_len: Determines the length of the address buffer.
If the function executes successfully, the return value is 0, otherwise socket_error.
Receive
Function Prototypes:
int recv(SOCKET socket, char FAR* buf, int len, int flags);
- Socket: A descriptive word that identifies the connected socket interface.
- BUF: The buffer used to receive data.
- Len: buffer length.
- Flags: Specifies the invocation method. Value: Msg_peek View the current data, the data will be copied into the buffer, but not removed from the input queue; Msg_oob processing out-of-band data.
If no error occurs, recv () returns the number of bytes read in. Returns 0 if the connection has been aborted. Otherwise, the SOCKET_ERROR error is returned, and the application can get the corresponding error code via WSAGETLASTERROR ().
Function Prototypes:
ssize_t recvfrom(int sockfd, void buf, int len, unsigned int flags, struct socketaddr* from, socket_t* fromlen);
- SOCKFD: Identifies a description word for a connected socket interface.
- BUF: Receives the data buffer.
- Len: buffer length.
- Flags: Invoke operation mode.
- From: (optional) pointer to the buffer containing the source address.
- Fromlen: (optional) pointer, pointing to the from buffer length value.
Send
Function Prototypes:
int sendto( SOCKET s, const char FAR* buf, int size, int flags, const struct sockaddr FAR* to, int tolen);
- S: Socket
- BUF: Buffer for data to be sent
- Size: Buffer length
- Flags: Call way flag bit, general 0, change flags, will change the form of sendto send
- Addr: (optional) pointer to the address of the destination socket
- Tolen:addr the length of the address referred to
If successful, returns the number of bytes sent, and the failure returns SOCKET_ERROR.
Receive connection requests
Function Prototypes:
int accept( int fd, struct socketaddr* addr, socklen_t* len);
- FD: Socket descriptor.
- Addr: Returns the connected address
- Len: The length of the buffer that receives the return address
Successful return of the client's file descriptor, failed to return-1.
The above content from Baidu
TCP Code implementation
TCP (transmission Control Protocol Transmission Protocol) is a connection-oriented, reliable, byte-stream-based Transport layer communication protocol.
So we need to know three handshakes and four breakup. Detailed explanations are available.
TCP Server
////MAIN.C//Socketserver////Created by Alps on 15/8/17.//Copyright (c) 2015 Chen. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <unistd.h>#ifndef Default_port#define Default_port 8001#endif#ifndef MAXLINE#define MAXLINE 4096#endifintMainintargcChar Const*argv[]) {intSOCKET_FD = socket (af_inet, Sock_stream,0);intCONNECT_FD;structSockaddr_in servaddr;Char*buffer = (Char*)malloc(MAXLINE *sizeof(Char));intRecv_len,write_len; FILE *FP = fopen ("/users/alps/desktop/recv.jpg","wb+");if(fp = = NULL) {printf("Open file error!\n");Exit(0); }if(SOCKET_FD = =-1) {printf("Create socket Error%s (errno:%d\n)", Strerror (errno), errno);Exit(0); }memset(&SERVADDR,0,sizeof(SERVADDR)); servaddr.sin_family = af_inet; SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);The //IP address is set to Inaddr_any, allowing the system to automatically get the IP address of the machine. Servaddr.sin_port = htons (Default_port);//Set the port to Default_port //Bind the local address to the socket you created if(Bind (SOCKET_FD, (structsockaddr*) &servaddr,sizeof(SERVADDR)) == -1){printf("bind socket Error:%s (errno:%d) \ n", Strerror (errno), errno);Exit(0); }//Start listening for a client connection if(Listen (SOCKET_FD,Ten) == -1){printf("Listen socket Error:%s (errno:%d) \ n", Strerror (errno), errno);Exit(0); }printf("======waiting for client ' s request======\n"); while(1){//block until there is a client connection, or more wasted CPU resources. if(connect_fd = Accept (SOCKET_FD, (structsockaddr*) (null)) = =-1){printf("Accept socket Error:%s (errno:%d)", Strerror (errno), errno);Continue; }//Accept data sent by clientBzero (buffer, MAXLINE); while(1) {Recv_len = (int) recv (connect_fd, buffer, MAXLINE,0);if(Recv_len <0) {printf("Receive Data from Client error!\n"); Break; }printf("%s\n", buffer); Write_len = (int) fwrite (buffer,sizeof(Char), Recv_len, FP);;if(Write_len < Recv_len) {printf("Write File failed!\n"); Break; } bzero (buffer, MAXLINE); } close (CONNECT_FD); Break; } close (SOCKET_FD);return 0;}
The above is the server code.
TCP Client
////MAIN.C//Socketclient////Created by Alps on 15/8/9.//Copyright (c) 2015 Chen. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#ifndef Default_port#define Default_port 8001#endif#define MAXLINE 4096#define IP "127.0.0.1"intMainintargcChar* * argv) {intSockfd,rec_len,send_len;Charrecvline[4096], sendline[4096];Char*buffer = (Char*)malloc(MAXLINE *sizeof(Char));structSockaddr_in servaddr; FILE *OUTFP = fopen ("/users/alps/desktop/socket.jpg","rb+");if(OUTFP = = NULL) {printf("Client Open File error!\n");Exit(0); }if(SOCKFD = socket (af_inet, Sock_stream,0)) <0){printf("Create socket Error:%s (errno:%d) \ n", Strerror (errno), errno);Exit(0); }memset(&SERVADDR,0,sizeof(SERVADDR)); servaddr.sin_family = af_inet; Servaddr.sin_port = htons (Default_port);if(Inet_pton (Af_inet, IP, &servaddr.sin_addr) <=0){printf("Inet_pton error for%s\n", argv[1]);Exit(0); }if(Connect (SOCKFD,structsockaddr*) &servaddr,sizeof(SERVADDR)) <0){printf("Connect Error:%s (errno:%d) \ n", Strerror (errno), errno);Exit(0); }//while (1) { printf("send file to server ... \ n"); while((Send_len = (int) fread (buffer,sizeof(Char), MAXLINE, OUTFP) >0){if(Send (SOCKFD, buffer, Send_len,0) <0) {printf("Send File error!\n"); Break; } bzero (buffer, MAXLINE); } close (SOCKFD);Exit(0);}
The above is the client code.
UDP Code Implementation
The full name of the UDP protocol is the User Datagram Protocol [1], which is a non-connected protocol for processing packets as the TCP protocol in the network. In the OSI model, the fourth layer, the transport layer, is in the upper layer of the IP protocol. UDP has the disadvantage of not providing packet grouping, assembling, and not ordering packets, that is, when the message is sent, it is not possible to know whether or not it arrives safely and completely.
So our UDP code is slightly different from TCP.
UDP Server
////MAIN.C//Udp_server////Created by Alps on 15/8/12.//Copyright (c) 2015 Chen. All rights reserved.//#include <stdio.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>intMainintargcChar**ARGV) {intSOCKFD;structSockaddr_in servaddr; SOCKFD = socket (pf_inet, SOCK_DGRAM,0); Bzero (&SERVADDR,sizeof(SERVADDR)); servaddr.sin_family = af_inet; SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Servaddr.sin_port = htons (50001); Bind (SOCKFD, (structSOCKADDR *) &servaddr,sizeof(SERVADDR));Charrecvline[1024x768]; Recvfrom (SOCKFD, Recvline,1024x768,0, NULL, NULL);printf("%s\n", Recvline); Close (SOCKFD);}
This is the server code.
UDP Client
////MAIN.C//Udp_client////Created by Alps on 15/8/12.//Copyright (c) 2015 Chen. All rights reserved.//#include <stdio.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>intMainintargcChar**ARGV) {intSOCKFD;structSockaddr_in servaddr; SOCKFD = socket (pf_inet, SOCK_DGRAM,0); Bzero (&SERVADDR,sizeof(SERVADDR)); servaddr.sin_family = af_inet; Servaddr.sin_port = htons (50001); SERVADDR.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");Charsendline[ -];sprintf(Sendline,"Hello, world!."); SendTo (SOCKFD, Sendline,strlen(Sendline),0, (structSOCKADDR *) &servaddr,sizeof(SERVADDR)); Close (SOCKFD);return 1;}
The above is the client code.
In fact, these two protocols are different, destined to be different is some way of sending and receiving. But in fact, the final receipt of data and the processing of sending data are the same.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Socket Programming (TCP/UDP)-Beginner (C language)