General steps for writing socket programs in unix

Source: Internet
Author: User
Tags localhost 8888 socket error htons
General steps for writing socket programs in unix-general Linux technology-Linux programming and kernel information. The following is a detailed description. Writing a socket program in unix may be the most convenient. You only need to master the general steps to write the application for the transport layer.

1. Understand several common socket Functions

# Include
# Include
Int socket (int domain, int type, int portocol );
Domain indicates that the protocol family used can be AF_UNIX and AF_INET. Generally, only AF_INET (Internet) type indicates the transmission type used. It can be SOCK_STERAM (connection-oriented TCP ), and SOCK_DGRAM (for connectionless udp)
Int bind (int s, const struct sockaddr * address, size_t address_len );
S is the file descriptor returned by the socket.
Address is the protocol family name and other information.
The specific structure is struct sockaddr_in {
Short sin_family;/* protocol family
U_short sin_port;/* port */
Struct in_addr sin_addr;/* address */
Char sin_zero [8];
};
Int listen (int s, int backlog );
Backlog is the allowed number of requests
Int accept (int s, struct sockaddr * address, int * address_len );
The first two parameters are the same as above.
Addres_len is an address that records the structure size.
Int connect (int s, struct sockaddr * address, size_t address_len );
The parameter meanings here are the same as those of bind.

2. Understand the general call process for establishing a program

To create a server program that processes the connection, you must first call the socket function to create a socket and return a file handle fd, so that subsequent operations on the socket function can be read and written like normal file devices.

Because the server must listen to requests from other machines for a fault, the bind function is called next, the fd is passed in, and the address and port are defined, because it is to accept connections from any host, it should be said that sin_addr is assigned as INADDR_ANY, and the port is the port you set.

Note: The address and port here are in the byte sequence of the network, so you need to call htonl and htons to complete the byte sequence of the host.
Change to network byte

The next step is to listen and call accept to accept requests from the client. accpet returns the connected file descriptor and you can use it to send and receive information (corresponding to read and write) this process is socket-> bind-> listen-> accpet-> Read, write
The client is socket-> connect-> read, write

3. A complete program

# Include
# Include
# Include/* Header files containing functions such as htons */

# Include
# Include

Void main ()
{
Int listenfd, clifd;
Long pid;
Struct sockaddr_in myaddr, cliaddr;

Int ret;
Int len;

Listenfd = socket (AF_INET, SOCK_STREAM, 0 );
If (listenfd <0)
{
Perror ("socket error ");
Exit (-1 );
}

Myaddr. sin_family = AF_INET;
Myaddr. sin_addr.s_addr = htonl (INADDR_ANY );
Myaddr. sin_port = htons (8888 );

Ret = bind (listenfd, (struct sockaddr *) & myaddr, sizeof (myaddr ));
If (ret <0)
{
Perror ("bind error ");
Exit (-1 );
}
Listen (listenfd, 10 );
Len = sizeof (struct sockaddr );
While (1)
{
Clifd = accept (listenfd, (struct sockaddr *) & cliaddr, & len );
/* Note that the third parameter of accept is also the address */
If (clifd =-1)
{
Perror ("accept error ");
Continue;
}
Printf ("connect from % s % d \ n", inet_ntoa (cliaddr. sin_addr.s_addr ),
Ntohs (cliaddr. sin_port ));

Switch (pid = fork ())
{
Case 0:/* sub-process */
Close (listenfd );
;/* Subprocesses perform other operations */
Close (clifd );
Exit (0 );
Break;
Case-1:
Perror ("fork error ");
Break;
Default:/* parent process */
Close (clifd );
Break;

}
}

}

4. program description

The function of this program is to listen to the connection of port 8888. For all the connections to port 8888, it shows the address and the port number of the other Party. This program is successfully debugged under sco unix, on other unix and linux platforms, pay attention to the header file name that the inet_ntoa and htons functions should contain.

At the same time, the program uses the concurrency point of view, because accept, read, write are all blocking (block) functions, once the process block will not be able to process other requests, so use the main process for listen, the sub-process is responsible for transmitting data to the client.

You can use telnet localhost 8888 on the same unix Machine for observation. The program will output connect from 127.0.0.1 xxxx.
Related Article

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.