Common functions and processes of Linux network programming

Source: Internet
Author: User
Tags htons

First, the TCP process of network programming

Server: Socket---BIND---listen---while (1) {---accept---recv---send---close---}---close

Client: Socket----------------------------------Connect---Send---recv-----------------close

Second, network programming commonly used functions

Server-side:

    1. The header file contains:

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <string.h>

#include <stdio.h>

#include <stdlib.h>

2. Socket function: Generates a set of interface descriptors.

Prototype: int socket (int domain,int type,int protocol);

Parameter: domain->{ af_inet: Ipv4 network protocol AF_INET6: IPV6 Network protocol}

TYPE->{TCP:sock_stream udp:sock_dgram}

protocol-> specifies the transport protocol number used by the socket. is usually 0.

Return value: Success returns a set of interface descriptors, failure returns-1.

Common examples: int sfd = socket (af_inet, sock_stream, 0);

if (sfd = =-1) {perror ("socket"); exit (-1);}

3. Bind function: Used to bind a port number and IP address, so that the socket interface with the specified port number and IP address associated.

Prototype: int bind (int sockfd,struct sockaddr * my_addr,int addrlen);

The parameter:sockfd-> is the return value of the preceding socket.

my_addr-> as struct pointer variable

Defines a common data structure for different socket domain
struct SOCKADDR//This struct is not commonly used
{
unsigned short int sa_family; The domain parameter when the socket () is called, which is the af_inet value.
Char sa_data[14]; Use a maximum of 14 character lengths
};
This SOCKADDR structure will have different structure definitions due to the use of different socket domain.
For example, using Af_inet domain, its socketaddr structure definition is
struct SOCKADDR_IN//Common structure
{
unsigned short int sin_family; That is the Sa_familyèaf_inet
uint16_t Sin_port; The port number to use
struct IN_ADDR sin_addr; For the IP address
unsigned char sin_zero[8]; Not used
};
struct IN_ADDR
{
uint32_t s_addr;
};
The structure length of the addrlen->sockaddr. is usually calculated sizeof (struct sockaddr);

Return value: Success returns 0, failure returns-1

Common examples: struct sockaddr_in my_addr; Defining struct-Body variables

memset (&my_addr, 0, sizeof (struct sockaddr)); Empty the structure

or bzero (&my_addr, sizeof (struct sockaddr));

my_addr.sin_family = af_inet; Represents the adoption of the IPV4 network protocol

My_addr.sin_port = htons (8888); Represents a port number of 8888, which is typically a value greater than 1024.

Htons () Converts the 16-bit hostshort specified by the parameter to the network character sequence

MY_ADDR.SIN_ADDR.S_ADDR = inet_addr ("192.168.0.101"); INET_ADDR () is used to convert the IP address string into a binary number used by the network, if inaddr_any, which means that the server automatically populates the native IP address.

if (Bind (SFD, (struct sockaddr*) &my_str, sizeof (struct socketaddr)) = =-1)

{perror ("bind"); Close (sfd); exit (-1);}

(Note: By placing My_addr.sin_port at 0, the function automatically selects an unoccupied port for you to use.) Similarly, by placing my_addr.sin_addr.s_addr as Inaddr_any, the system automatically fills in the native IP address. )

4. Listen function: Make this port and IP of the server in listening state, waiting for the connection request of a client in the network. If the client has a connection request, the port accepts the connection.

Prototype: int listen (int sockfd,int backlog);

The parameter:sockfd-> is the return value of the preceding socket. namely SFD

The backlog-> specifies the maximum connection requirement that can be processed at the same time, typically 10 or 5. Maximum value can be set to 128

Return value: Success returns 0, failure returns-1

Common examples: if (Listen (SFD, 10) = =-1)

{Perror ("listen"); Close (sfd); exit (-1);}

5. Accept function: Accepts the connection request from the remote computer and establishes a communication connection with the client. When the server is listening, if the client's connection request is received at some point, the request is not processed immediately, but the request is placed in the waiting queue and the client's connection request is processed when the system is idle. When the Accept function accepts a connection, a new socket identifier is returned, and subsequent data transfers and reads are processed by the new socket number, and the socket in the original parameter can continue to be used to listen to other client connection requests. (that is, similar to the mobile business, if a customer calls 10086, the server will request a connection, processing some transactions, notify an operator to answer the customer's call, that is, all the subsequent operations, at this time has no relationship with the server, but the operator and the customer's communication. corresponding to the customer request to connect our server, our server did some binding and listening and so on, if the connection is allowed, then call the Accept function to generate a new socket, and then use this new socket with our customers to send and receive data. That is, the server has a successful connection with a client, and there are two sockets. )

Prototype: int accept (int s,struct sockaddr * addr,int * addrlen);

The parameter:s-> is the return value of the preceding socket. namely SFD

Addr-> is a struct pointer variable, and the struct of bind is the same type, the system will store the remote host's information (the remote host's address and port number information) to this pointer refers to the structure of the body.

Addrlen-> represents the length of the struct as an integer pointer

Return value: Success returns new socket processing code NEW_FD, failed return-1

Common examples: struct sockaddr_in clientaddr;

memset (&clientaddr, 0, sizeof (struct sockaddr));

int addrlen = sizeof (struct sockaddr);

int new_fd = Accept (sfd, (struct sockaddr*) &clientaddr, &addrlen);

if (new_fd = =-1)

{perror ("accept"); Close (sfd); exit (-1);}

printf ("%s%d success connect\n", Inet_ntoa (CLIENTADDR.SIN_ADDR), Ntohs (Clientaddr.sin_port));

6. recv function: Use the new socket to receive data from the remote host and save the data to the memory space pointed by the parameter buf

Prototype: int recv (int sockfd,void *buf,int len,unsigned int flags);

The parameter:sockfd-> is the return value of the preceding accept. That is, NEW_FD, which is the new socket.

Buf-> represents a buffer

Len-> indicates the length of the buffer

Flags-> is typically 0

Return value: Success returns the actual number of characters received, which may be less than the receive length you specify. Failed return-1

Common example: char buf[512] = {0};

if (recv (NEW_FD, buf, sizeof (BUF), 0) = =-1)

{perror ("recv"); Close (NEW_FD); close (sfd); exit (-1);}

Puts (BUF);

7. Send function: Send data to the specified remote host with a new socket

Prototype: int send (int s,const void * Msg,int len,unsigned int flags);

The parameter:s-> is the return value of the preceding accept. that is NEW_FD

Msg-> is generally a constant string

len-> indicates length

Flags-> is typically 0

Return value: Success returns the actual number of characters sent, which may be less than the send length you specified. Failed return-1

Common examples: if (send (NEW_FD, "Hello", 6, 0) = =-1)

{perror ("send"); Close (NEW_FD); close (sfd); exit (-1);}

8. Close function: When you are finished using the file, you can close the file using close () if it is no longer needed, and close () causes the data to be written back to disk and frees the resources that the file occupies

Prototype: int close (int fd);

The parameter:fd-> is the previous sfd,new_fd

Return value: Returns 0 if the file is closed successfully, returns 1 if an error occurs

Common examples: close (NEW_FD);

Close (SFD);

Client:

1. Connect function: Used to request a connection to a remote server, connect the socket of the parameter SOCKFD to the server IP and port number specified in the parameter serv_addr.

Prototype: int connect (int sockfd,struct sockaddr * serv_addr,int addrlen);

The parameter:sockfd-> is the return value of the preceding socket, which is the SFD

Serv_addr-> is a struct pointer variable that stores the IP and port number information for a remote server.

Addrlen-> represents the length of a struct variable

Return value: Success returns 0, failure returns-1

Common example: struct sockaddr_in seraddr;//Request Connection Server

memset (&seraddr, 0, sizeof (struct sockaddr));

seraddr.sin_family = af_inet;

Seraddr.sin_port = htons (8888); Port number of the server

SERADDR.SIN_ADDR.S_ADDR = inet_addr ("192.168.0.101"); The IP of the server

if (Connect (SFD, (struct sockaddr*) &seraddr, sizeof (struct sockaddr)) = =-1)

{perror ("connect"); Close (sfd); exit (-1);}

Common functions and processes of Linux network programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.