Linux network programming notes

Source: Internet
Author: User
1 client Program And server programs
The biggest difference between a network program and a common program is that a network program consists of two parts: the client and the server.
A network program starts a server program and waits for the client program to run and establish a connection. Generally, the server program listens on a port until a client program sends a request.

2. Common commands
Netstat
The netstat command is used to display network connection, route table and interface statistics, and other network information. netstat has many options. The commonly used option is-an to display the detailed network status. for other options, we can use the help manual for details.

Telnet
Telnet is a remote control program, but we can use this program to debug our server program. for example, if our server program is listening to port 8888, we can use Telnet localhost 8888 to check the server status.

3 Introduction to TCP/UDP
TCP (Transfer Control Protocol) is a connection-oriented protocol. When our network programs use this protocol, the network ensures that the connection between our client and the server is reliable and secure.

User Data Protocol (UDP) is a non-connection-oriented protocol, which cannot ensure that the connection of our network programs is reliable, therefore, the program we write now generally uses the TCP protocol.

4 in Linux, network programming is implemented through socket. network programs call socket and several other functions to return a communication file descriptor. we can regard this descriptor as a common file descriptor for operation, this is the benefit of Linux's device independence. we can exchange data between networks by reading and writing the descriptor.

There are two common socket types: stream socket (sock_stream) and datagram socket (sock_dgram ). Streaming is a connection-oriented socket for connection-oriented TCP Service applications; datagram socket is a connectionless socket that corresponds to connectionless UDP Service applications.

Common functions:
Socket bind connect accept listen

Int socket (INT domain, int type, int Protocol)

Domain indicates the protocol family used, usually pf_inet, indicating the Internet protocol family (TCP/IP protocol family). The type parameter specifies the socket type: sock_stream or sock_dgram, the socket interface also defines the original socket (sock_raw), which allows the program to use the lower-layer protocol; Protocol is usually assigned "0 ". The socket () call returns an integer socket descriptor, which you can use later.
The socket descriptor is a pointer to the internal data structure and points to the descriptor table entry. When the socket function is called, the socket execution body establishes a socket. In fact, "Creating a socket" means allocating storage space for a socket data structure. The socket execution body manages the descriptor table for you.
A network connection between two network programs includes five types of information: communication protocol, local Protocol address, local host port, remote host address, and remote protocol port. The socket data structure contains these five types of information.

Int BIND (INT sockfd, struct sockaddr * my_addr, int addrlen)

sockfd is the socket descriptor returned by calling the socket function. my_addr is a sockaddr pointer pointing to information including the local IP address and port number; addrlen is often set to sizeof (struct sockaddr ).
the struct sockaddr structure is used to save socket information:
struct sockaddr {
unsigned short sa_family;/* address family, af_xxx */
char sa_data [14];/* 14-byte Protocol address */
};
there is also a structure type:
struct sockaddr_in {
short int sin_family;/* address family */
unsigned short int sin_port;/* Port Number */
struct in_addr sin_addr; /* IP Address */
unsigned char sin_zero [8];/* fill in 0 to keep the same size as struct sockaddr */
};
this structure is more convenient to use. Sin_zero is used to fill the sockaddr_in structure with the same length as struct sockaddr. It can be set to zero using the bzero () or memset () function. The pointer to sockaddr_in and the pointer to sockaddr can be converted to each other, which means that if the parameter type required by a function is sockaddr, you can convert a pointer to sockaddr_in to a pointer to sockaddr when calling a function; or vice versa.

When using the BIND function, you can use the following value assignment to automatically obtain the local IP address and randomly obtain an unused port number:
My_addr.sin_port = 0;/* The system randomly selects an unused Port Number */
My_addr.sin_addr.s_addr = inaddr_any;/* enter the local IP Address */
By setting my_addr.sin_port to 0, the function automatically selects an unused port for you to use. Similarly, by setting my_addr.sin_addr.s_addr to inaddr_any, the system automatically fills in the local IP address.
Note that when using the BIND function, you need to convert sin_port and sin_addr to the network byte priority, while sin_addr does not need to be converted.

Int listen (INT sockfd, int backlog)

Sockfd: The file descriptor after bind.

Backlog: set the maximum length of the Request queue. when multiple client programs are connected to the server, use this to indicate the length of the queue. the listen function changes the file descriptor of bind to the listening socket. the returned result is the same as that of BIND.

Int accept (INT sockfd, struct sockaddr * ADDR, int * addrlen)

Sockfd: The file descriptor after listen.

ADDR and addrlen are used to fill in the client program. The server only needs to pass the pointer. BIND, listen, and accept are functions used by the server. When an accept is called, the server program will be blocked until a client program sends a connection. when accept succeeds, the final server file descriptor is returned. At this time, the server can write information to this descriptor. -1 is returned when a failure occurs.

Int connect (INT sockfd, struct sockaddr * serv_addr, int addrlen)

Sockfd: file descriptor returned by the socket.

Serv_addr: stores the connection information of the server. sin_add is the address of the server.

Addrlen: length of serv_addr

The connect function is used by the client to connect to the server. 0 is returned when the connection is successful, and-1 is returned when the file descriptor for communication with the server fails.
Sockfd is the socket descriptor returned by the socket function, serv_addr is a pointer containing the IP address and port number of the remote host, and addrlen is the length of the remote geological structure. When an error occurs, the connect function returns-1 and sets errno as the corresponding error code. For client program design, you do not need to call BIND (), because in this case, you only need to know the IP address of the target machine, and you do not need to care about which port the customer uses to establish a connection with the server, the socket execution body automatically selects an unused port for your program and notifies you when the program data is interrupted.
Connect function starts a direct connection with the remote host. The socket must be connected to the remote host only when the connection-oriented client program uses the socket. No connection protocol never establishes direct connection. The connection-oriented server never starts a connection, but passively listens to customer requests on the protocol port.

The client first obtains the Server IP address through the server domain name, creates a socket, calls the connect function to establish a connection with the server, receives data sent from the server after the connection is successful, and closes the socket.
The gethostbyname () function completes domain name conversion. Because IP addresses are hard to remember and read/write, domain names are often used to represent hosts for convenience, which requires domain name and IP address conversion. Function prototype:
Struct hostent * gethostbyname (const char * Name );
The structure type returned by the function as hosten. Its definition is as follows:
Struct hostent {
Char * h_name;/* Host's official domain name */
Char ** h_aliases;/* an array of host aliases ending with null */
Int h_addrtype;/* return address type, in the Internet environment is AF-INET */
Int h_length;/* the length of the address in bytes */
Char ** h_addr_list;/* an array ending with 0, containing all addresses of the Host */
};
# Define h_addr h_addr_list [0]/* The first address in H-ADDR-list */
When gethostname () is called successfully, a pointer to struct hosten is returned. If the call fails,-1 is returned. When gethostbyname is called, you cannot use the perror () function to output error information. Instead, use the herror () function to output error information.

The principle of a connectionless client/server program is the same as that of a connected Client/Server. The difference between the two is that customers in a connectionless Client/Server generally do not need to establish a connection, when sending and receiving data, you must specify the address of the remote machine.

POP3 client instance

The followingCodeThe instance is connected to the mail server based on the POP3 client protocol and retrieves emails from the specified user account. Commands that interact with the email server are stored in the string array popmessage. The program sends these commands in sequence through a do-while loop.

 

# Include < Stdio. h >
# Include < Stdlib. h >
# Include < Errno. h >
# Include < String . H >
# Include < Netdb. h >
# Include < Sys / Types. h >
# Include < Netinet / In . H >
# Include < Sys / Socket. h >
# Define Pop3servport 110
# Define Maxdatasize 4096

Main ( Int Argc, Char   * Argv []) {
Int Sockfd;
Struct Hostent * Host;
Struct Sockaddr_in serv_addr;
Char   * Popmessage [] = {
" User userid \ r \ n " ,
" Pass password \ r \ n " ,
" Stat \ r \ n " ,
" List \ r \ n " ,
" RETR 1 \ r \ n " ,
" Dele 1 \ r \ n " ,
" Quit \ r \ n " ,
Null
};
Int Ilength;
Int Imsg = 0 ;
Int Iend = 0 ;
Char Buf [maxdatasize];

If (Host = Gethostbyname ( " Your. Server " )) = Null ){
Perror ( " Gethostbyname Error " );
Exit ( 1 );
}
If (Sockfd = Socket (af_inet, sock_stream, 0 )) =   - 1 ){
Perror ( " Socket Error " );
Exit ( 1 );
}
Serv_addr.sin_family = Af_inet;
Serv_addr.sin_port = Htons (pop3servport );
Serv_addr.sin_addr =   * (( Struct In_addr * ) Host -> H_addr );
Bzero ( & (Serv_addr.sin_zero ), 8 );
If (Connect (sockfd ,( Struct Sockaddr * ) & Serv_addr, Sizeof ( Struct Sockaddr )) =- 1 ){
Perror ( " Connect Error " );
Exit ( 1 );
}

Do{
Send (sockfd, popmessage [imsg], strlen (popmessage [imsg]),0);
Printf ("Have sent: % s", Popmessage [imsg]);

ilength = Recv (sockfd, buf + iend, sizeof (BUF) - iend, 0 );
iend += ilength;
Buf [iend] = ' \ 0 ' ;< br> printf ( " Received: % s, % d \ n " , Buf, imsg);

Imsg++;
}While(Popmessage [imsg]);

Close (sockfd );
}

 

 

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.