[Linux programming] BSD socket Quick Start manual

Source: Internet
Author: User
Tags htons

BSD socket Quick Start manual

  • Introduction
  • Analogy (what is socket ?)
  • Install your new phone number (how to listen ?)
  • Dialing (how to call socket)
  • Conversation (how to talk through sockets)
  • Suspend (end)
  • World Language (the language of communication is very important)
  • The future is under your control (next step ?)



When you enter the mysterious world of UNIX, you will immediately find more and more things difficult

Understanding. For most people, the concept of BSD socket is one of them. This is a very short tutorial to explain what they are, how they work, and give some simple code to explain how to use them.

Analogy (what is socket ?)

SocketIs the BSD Method for inter-program communication (IPC. This means that the socket is used to allow a process to communicate with other processes, just as we communicate with others by phone.

It is quite appropriate to use telephone to describe socket in the future.

Install your new phone number (how to listen ?)

To receive a call from someone else, first install a call. Similarly, you must first establish a socket to listen on the line. This process involves several steps. First, you need to create a new socket, just like installing a phone number first.socket()Command.

Because sockets has several types, you need to specify the type you want to establish. You need to select the socket address format. Just as the phone has two forms of audio and pulse, socket has two most important options:Af_unixAndIaf_inet.Af_unixRecognize sockets just like a Unix path name. This form is useful for IPC on the same machine. WhileAf_inetThe address format of the four decimal numbers separated by periods, such as In addition to the machine address, you can also use the port number to allow multipleAf_inetSocket. We will focus onAf_inetBecause it is very useful and widely used.

The other parameter you must provide is the socket type. Two important types are:Sock_streamAndSock_dgram.Sock_streamIt indicates that the data passes through socket like a ghost stream. WhileSock_dgramIt indicates that the data is a datagram (Datagrams. We will explainSock_streamSockets, which is common and easy to use.

After a socket is created, we need to provide the socket listening address. Just like you need a phone number to pick up your phone.bind()Function.

Sock_stream sockets forms a queue for connection requests. If you are busy processing a connection, other connection requests will wait until the connection is processed.listen()The function is used to set the maximum number of requests not rejected (generally five ). Generally, it is best not to uselisten()Function.

The following code describes how to usesocket(),bind()Andlisten()The function establishes a connection and can accept data.


/* Code to establish a socket; originally from bzs@bu-cs.bu.edu */INT establish (unsigned short portnum) {char myname [maxhostname + 1]; int s; struct sockaddr_in SA; struct hostent * HP; memset (& SA, 0, sizeof (struct sockaddr_in);/* clear our address */gethostname (myname, maxhostname);/* Who Are We? */HP = gethostbyname (myname);/* Get our address info */If (HP = NULL)/* We don't exist !? */Return (-1); SA. sin_family = hp-> h_addrtype;/* this is our host address */SA. sin_port = htons (portnum);/* this is our port number */If (S = socket (af_inet, sock_stream, 0) <0) /* Create socket */Return (-1); If (BIND (S, & SA, sizeof (struct sockaddr_in) <0) {close (s ); return (-1);/* Bind Address to socket */} Listen (s, 3);/* max # Of queued connects */Return (s );}

After the socket is created, you have to wait for the socket to be called.accept()Function for this purpose. Callaccept()It is like bringing up a call after the phone rings.Accept()Returns a new socket to connect to the caller.

The following code demonstrates how to use it.


/* Wait for a connection to occur on a socket created with establish () */INT get_connection (INT s) {int T; /* socket of connection */If (t = accept (S, null, null) <0)/* accept connection if there is one */Return (-1 ); return (t );}

Different from the phone number, you can accept the call when you process the previous connection. Therefore, fork is generally used to process each connection. The following code demonstrates how to useestablish()Andget_connection()To process multiple connections.


# Include <errno. h>/* obligatory includes */# include <signal. h> # include <stdio. h> # include <unistd. h> # include <sys/types. h> # include <sys/socket. h> # include <sys/Wait. h> # include <netinet/in. h> # include <netdb. h> # define portnum 50000/* random port number, we need something */void fireman (void); void do_something (INT); main () {int S, T; if (S = Establish (portnum) <0) {/* plug in the phone */perror ("establish"); exit (1);} signal (sigchld, fireman);/* This eliminates zombies */For (;) {/* loop for phone cballs */If (t = get_connection (s) <0) {/* get a connection */If (errno = eintr)/* eintr might happen on accept (), */continue; /* try again */perror ("accept");/* bad */exit (1);} switch (Fork ()) {/* try to handle connection */case-1:/* Bad News. scream and die */perror ("fork"); close (s); close (t); exit (1); case 0:/* We're re the child, do something */close (s); do_something (t); exit (0); default:/* We're re the parent so look for */close (t ); /* another connection */continue; }}/ * as children die we shoshould get catch their returns or else we get * zombies, a bad thing. fireman () catches falling children. */void fireman (void) {While (waitpid (-1, null, wnohang)> 0);}/* This is the function that plays with the socket. it will be called * after getting a connection. */void do_something (INT s) {/* do your thing with the socket here ::*/}

Dialing (how to call socket)

Now you should know how to establish a socket to accept the call. So how to call it? Like a phone number, you must have a phone number first. Usesocket()Function to do this, just like creating a socket for listening.

After giving the socket address, you can useconnect()Function to connect the listening socket. Below is a piece of code.


Int call_socket (char * hostname, unsigned short portnum) {struct sockaddr_in SA; struct hostent * HP; int A, s; If (HP = gethostbyname (hostname) = NULL) {/* do we know the host's */errno = econnrefused;/* address? */Return (-1);/* No */} memset (& SA, 0, sizeof (SA); memcpy (char *) & SA. sin_addr, HP-> h_addr, HP-> h_length);/* Set address */SA. sin_family = hp-> h_addrtype; SA. sin_port = htons (u_short) portnum); If (S = socket (HP-> h_addrtype, sock_stream, 0) <0) /* Get socket */Return (-1); If (connect (S, & SA, sizeof SA) <0) {/* connect */close (s ); return (-1);} return (s );}

This function returns a socket that can flow through data.

Conversation (how to talk through sockets)

Now you have established a connection between the two parties that want to transmit the data.read()Andwrite()Function. In addition to the difference between socket reading and writing and file reading and writing, it is the same as processing common files. The difference is that you generally cannot get the data you want. So you need to keep repeating to the arrival of the data you need. A simple example: Read data to the cache.


Int read_data (int s,/* connected socket */char * Buf,/* pointer to the buffer */int n/* number of characters (bytes) We want */) {int bcount;/* counts bytes read */int br;/* bytes read this pass */bcount = 0; BR = 0; while (bcount <n) {/* loop until full buffer */If (BR = read (S, Buf, N-bcount)> 0) {bcount + = BR; /* increment byte counter */BUF + = BR;/* Move buffer PTR for next read */} else if (BR <0) /* signal an error to the caller */Return (-1);} return (bcount );}

You can write data for the same function.

Suspend (end)

Like when you talk to someone by phone, you need to close the connection between sockets. Averageclose()The function is used to close socket connections on each side. If one side is disabled while the other side is writing data to it, an error code is returned.

World Language (the language of communication is very important)

Now you can contact the machine, but be careful with what you said. Many machines have their own dialects, such as ASCII and ebcdic. The more common problem is the byte order. Unless you have always transmitted text, you must pay attention to this problem. Fortunately, people have found a solution.

Long ago, people argued which order was more "correct ". Now it is necessary to have corresponding functions for conversion. There arehtons(),ntohs(),htonl()Andntohl(). Before transmitting an integer data, convert it.


I = htonl (I); write_data (S, & I, sizeof (I ));

After reading the data, change it back.


Read_data (S, & I, sizeof (I); I = ntohl (I );

If you keep sticking to this habit, you will have fewer chances of making mistakes than others.

The future is under your control (next step ?)

With what we have discussed, you can write your own communication program. Like all new things, it is best to see what others have done. There are many things about BSD socket for reference.

Please note that there is no error check in the example, which is very important in the "real" program. You should pay full attention to this.

Previous Article: Secure port allocation for Linux Device Drivers: Linux socket programming
Next article: [Linux programming] Linux/Unix Process Creation

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.