Linux socket development Basics

Source: Internet
Author: User
 
 

This is the first article in a series about how to use various available interfaces to develop network programs for Linux. Like most UNIX-based operating systems, Linux supports using TCP/IP as the local network transmission protocol. In this series, we assume that you are familiar with C Programming on Linux and some system knowledge on Linux, such as signals and forking.

This article describes how to use BSD interfaces to create network programs. In the next article, we will solve the problem of establishing (network) deamon processes. In the future, we will also discuss Using Remote Procedure Call (RPC) and using CORBA/distributed objects for development.

  I. Introduction to TCP/IP

The TCP/IP protocol family allows two programs running on the same computer or two computers connected by the network to communicate. This protocol family is designed for communication on unreliable networks. TCP/IP allows two basic operation modes: connection-oriented reliable transmission (TCP) and connectionless transmission (UDP ).

TCP provides a sequential, reliable, bidirectional (bi-directional), and connection-based byte transmission stream with a relay function transparent to upper-layer protocols. TCP splits your information into a datagram (not greater than 64 KB) and ensures that all the datagram entries arrive at the destination in order. Because it is based on connections, a virtual connection must be established before communication between one network entity and the other. On the contrary, UDP provides a (very fast) connectionless and unreliable message transmission (the message size is a definite maximum length ).

In order for programs to communicate with each other, no matter whether they are on the same machine (through the loopback interface) or different hosts, each program must have an independent address.

A TCP/IP address consists of two parts: the IP address used to identify the machine and the port address used to identify the specific program on that machine.

The address can be in the dotted-Quad format (for example, 127.0.0.1) or host name format (for example, www.csdn.net ). The system can use/etc/hosts or DNS Domain Name Service (if possible) to convert the host name to the point-to-point signed address (that is, the IP address.

Port Number starts from 1. 1 and ipp0rt_reserved (in/usr/include/netinet/in. the CIDR Block in H, usually 1024) is reserved for the system (that is, you must create a network service as root to bind this part of the port ).

Most of the simplest network programs use the customer-server model. A service process waits for a client process to connect to it. When a connection is established, the server executes a specific task on behalf of the customer, which usually interrupts the connection.

  Ii. Use the BSD Interface

The most common TCP/IP programming method is to use BSD interface programming. Through it, network endpoints (IP addresses and port addresses) appear in the form of a set of interfaces (sockets.

This set of interface IPC (interprocess communication) Facilities (introduced from 4.2bsd) is designed to allow the design of network programs to be independent of different underlying communication facilities.

1. Create a server program

To create a server program on the BSD interface, follow these steps:

(1) Establish a set of interfaces through function socket ()
(2) bind an address (IP address and port address) through the function BIND ). In this step, the server location is determined so that the client can know how to access the server.
(3) Use the listem () function to listen to new connection requests from the listen port.
(4) use the accept () function to accept new connections.

Generally, maintenance means that the customer's request may take a long time. When processing a request, it is also efficient to receive and process new requests. The most common way to achieve this is to allow the server to copy its own process through the fork () function to accept new connections.

The following example shows how the server is implemented in C:

<Br/>/* <br/> * simple "Hello, world! "Server <br/> * Ivan Griffin (ivan.griffin@ul.ie) <br/> */</P> <p>/* hellwolf misty translated */</P> <p> # include/**/<br/> # include/ * exit () */<br/> # include/* memset (), memcpy () */<br/> # include/* uname () */<br/> # include/* socket (), BIND (), <br/> listen (), accept () */<br/> # include/* fork (), write (), close () */</P> <p>/* <br/> * constan TS <br/> */<br/> const char message [] = "Hello, world! /N "; <br/> const int back_log = 5; </P> <p>/* <br/> * The program requires a command line parameter: port number to be bound <br/> */<br/> int main (INT argc, char * argv []) <br/>{< br/> int serversocket = 0, <br/> On = 0, <br/> Port = 0, <br/> Status = 0, <br/> childpid = 0; <br/> struct hostent * hostptr = NULL; <br/> char hostname [80] = ""; <br/> struct sockaddr_in servername = {0 }; </P> <p> If (2! = Argc) <br/>{< br/> fprintf (stderr, "Usage: % s/n", <br/> argv [0]); <br/> exit (1); <br/>}< br/> Port = atoi (argv [1]); <br/>/* <br/> * socket () system call with three parameters: <br/> * 1. The parameter domain indicates the communication domain, such as pf_unix (UNIX domain), pf_inet (IPv4), <br/> * pf_inet6 (IPv6), and so on <br/> * 2. type indicates the communication type, the most common ones are sock_stream (connection-oriented reliability mode, <br/> * For example, TCP) and sock_dgram (non-connection-oriented unreliable mode, such as UDP. <Br/> * 3. The Protocol parameter specifies the Protocol to be used. Although you can specify different protocols for the same protocol <br/> * family (protocol family) (or communication domain) <br/> *, there is usually only one. For TCP Parameters, you can specify ipproto_tcp. For <br/> * UDP, you can use ipproto_udp. You do not need to explicitly set this parameter. If 0 is used, the default protocol is used based on the preceding <br/> * parameters. <Br/> */<br/> serversocket = socket (pf_inet, sock_stream, <br/> ipproto_tcp); <br/> If (-1 = serversocket) <br/>{< br/> perror ("socket ()"); <br/> exit (1 ); <br/>}< br/> <br/>/* <br/> * once a set of interfaces are established, its operation mechanism can be set through socket option). <Br/> */</P> <p>/* <br/> * set the so_reuseaddr option to re-use the old address (IP address and port number) <br/> * Note: in Linux, if a socket is bound to a port, the socket is normally closed or the program exits, <br/> * The port remains bound for a period of time. Other programs (or the original program that restarts) cannot bind the port. <Br/> * in the following call: sol_socket indicates the operation on the socket layer <br/> */<br/> On = 1; </P> <p> Status = setsockopt (serversocket, sol_socket, <br/> so_reuseaddr, <br/> (const char *) & on, sizeof (on )); </P> <p> If (-1 = status) <br/> {<br/> perror ("setsockopt (..., so_reuseaddr ,...) "); <br/>}</P> <p>/* when the connection is interrupted, you must delay the linger operation) to ensure that all data <br/> * is transmitted, You need to enable the so_linger option <br/> * The linger structure is in/usr/include/Linux/socket. h: <br/> * Struct linger <br/> * {<br/> * int l_onoff;/* Linger active */<br/> * int l_linger; /* how long to linger */<br/> *}; <br/> * If l_onoff is 0, the feature will be canceled when it is delayed. If the value is not zero, the interface delay is allowed to be disabled. <Br/> * The l_linger field indicates the time when the delay is disabled. <br/> */</P> <p >{< br/> struct linger = {0 }; </P> <p> linger. l_onoff = 1; <br/> linger. rochelle linger = 30; <br/> Status = setsockopt (serversocket, <br/> sol_socket, so_linger, <br/> (const char *) & linger, <br/> sizeof (linger); </P> <p> If (-1 = Status) <br/>{< br/> perror ("setsockopt (..., so_linger ,...) "); <br/>}</P> <p>/* <br/> * find out who I am <br/> */ </P> <p> Status = gethostname (hostname, <br/> sizeof (hostname); <br/> If (-1 = Status) <br/>{< br/> perror ("gethostname ()"); <br/> exit (1 ); <br/>}</P> <p> hostptr = gethostbyname (hostname); <br/> If (null = hostptr) <br/>{< br/> perror ("gethostbyname ()"); <br/> exit (1 ); <br/>}</P> <p> (void) memset (& servername, 0, <br/> sizeof (servername); <br/> (void) memcpy (& servername. sin_addr, <br/> hostp Tr-> h_addr, <br/> hostptr-> h_length); <br/>/* <br/> * h_addr is a synonym for h_addr_list [0, <br/> * h_addr_list is an array of addresses. <br/> * The length is 4 (byte) represents the length of an IP address <br/> */<br/>/* <br/> * to bind the server to all the IP addresses of the local machine, <br/> * The above line of code should be replaced by the following code <br/> * servername. sin_addr.s_addr = htonl (inaddr_any); <br/> */</P> <p> servername. sin_family = af_inet; <br/>/* htons: H (host byteorder, host byteorder) <br/> * to n (Network byteorder, network byte order <br/> * s (shor T type) <br/> */<br/> servername. sin_port = htons (port); <br/>/* in an address (serversocket in this example) after it is created <br/> * It should be bound to the set of interfaces we obtain. <Br/> */<br/> Status = BIND (serversocket, <br/> (struct sockaddr *) & servername, <br/> sizeof (servername )); <br/> If (-1 = status) <br/>{< br/> perror ("BIND ()"); <br/> exit (1 ); <br/>}< br/>/* the current set of interfaces can be used to listen for new connections. <Br/> * back_log specifies the maximum length of the listen queue for pending connections <br/>. When a new connection arrives and the queue is full, the customer will receive a connection rejection error. <Br/> * (this is the basis for DOS DoS attacks ). <Br/> */<br/> Status = listen (serversocket, back_log); <br/> If (-1 = Status) <br/>{< br/> perror ("Listen ()"); <br/> exit (1 ); <br/>}< br/>/* starting from here, the set of interfaces is ready to accept requests and serve them. <Br/> * This example uses the for loop to achieve this goal. Once the connection is accepted (accpepted), <br/> * the server can obtain the customer's address through a pointer to perform some tasks such as recording Customer Login <br/>. <Br/> for (;) <br/>{< br/> struct sockaddr_in clientname = {0}; <br/> int slavesocket, clientlength = <br/> sizeof (clientname); </P> <p> (void) memset (& clientname, 0, <br/> sizeof (clientname )); </P> <p> slavesocket = accept (serversocket, <br/> (struct sockaddr *) & clientname, <br/> & clientlength ); <br/> If (-1 = slavesocket) <br/> {<br/> perror ("accept ()"); <br/> exit (1 ); <br/>}</P> <p> childpid = Fork (); </P> <p> switch (childpid) <br/>{< br/> case-1: /* Error */<br/> perror ("fork ()"); <br/> exit (1); </P> <p> case 0: /* child process */</P> <p> close (serversocket); </P> <p> If (-1 = getpeername (slavesocket, <br/> (struct sockaddr *) & clientname, <br/> & clientlength) <br/>{< br/> perror ("getpeername ()"); <br/>}< br/> else <br/> {<br/> printf ("connection request from % s/n", <br/> inet_nt OA (clientname. sin_addr); <br/>}</P> <p>/* <br/> * server application specific code <br/> * goes here, e.g. perform some <br/> * Action, respond to client etc. <br/> */<br/> write (slavesocket, message, <br/> strlen (Message )); <br/>/* You can also use the cached ANSI function fprint, <br/> * use fflush to refresh the cache if necessary <br/> */<br/> close (slavesocket); <br/> exit (0 ); </P> <p> default:/* parent process */<br/> close (slavesocket ); /* This is a good habit <br/> * Set interface descriptor of the parent process to disable the child process <br/> * just as the parent process to disable the parent process's set interface descriptor. <Br/> */<br/>}</P> <p> return 0; <br/>}</P> <p>

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.