Realization of socket in experiment--tcp of communication network

Source: Internet
Author: User
Tags socket error server port htons

I. Purpose of the experiment

1. Familiar with socket programming commands.

2. Lay a good foundation for the next experiment.

Second, the experimental principle

1. Network programming is through the computer network and other programs to communicate the program, socket programming is the mainstream network programming tools.

The 2.Socket API is a programming facility for interprocess communication and a mechanism for providing low-level abstraction between processes.

3. Although it is rare for application developers to write code at this level, it is important to understand the socket API. There are two main reasons:

First, high-rise facilities are built on the socket API, which is implemented using the operations provided by the socket API.

Second, even the socket API is the only available interprocess communication facility for applications that require higher response time or run on a limited resource platform.

The 4.socket API appeared in the early the 1980s as the Berkeley Unix (BSD 4.2) operating system library for interprocess communication.

5. The main operating system now provides the socket API. In Unix based systems, such as BSD, Linux systems, the socket API is part of the operating system kernel; In MS-DOS, Windows OS, OS/2, and other operating systems, the socket API is provided in the form of a library, as in a Windows system, The socket API is called Winsock.

6.Socket interface specification can be applied to a variety of communication protocols, mainly TCP/IP. TCP/IP is the most commonly used network communication protocol for computer interconnection, the core of TCP/IP is implemented by the kernel of network operating system, and the application accesses TCP/IP through programming interface.

7.TCP/IP uses a network address and a service port number to uniquely identify the device.

8. The network address identifies a specific device on the network; the port number identifies the specific service on the device to which you want to connect.

9. The basic mode of network communication is as follows: Each host of communication has a unique IP address in this network environment, a host often has multiple communication programs exist, each such program will occupy a communication port.

10. Therefore, an IP address, a communication port, can determine the location of a communication program.

Iii. contents of the experiment

Let's look at the implementation of a simple client/server program that sends messages on a TCP connection with a socket interface. This program also uses other UNIX networking features, which we'll be introducing one after another. Our application allows users to enter and send Wenbenfal to a user on one end of the machine. It is a simplified version of talk in Unix, similar to the core program of a web chat room.

Client

Let's start with the client, which uses the remote machine name as an argument. It calls gethostbyname to convert the name to the IP address of the remote host. The next step is to construct the address data structure (SIN) required by the socket interface. Note that this data structure indicates that we will always connect with the Internet (AF_INET) with sockets. In this example, we use the TCP port number 5432 as a shared server port number, which is not exactly the port number assigned to other Internet services. The final step in establishing a connection is to invoke the socket and connect. Once the connect operation is returned and the connection is established, the client program will enter the main loop, continuously reading the text from the standard input and sending it through the socket.

Server

The implementation of the server is also simple. First, it fills in its own port number (Server_port) to construct the address data structure. Second, it does not specify an IP address, which allows an application to accept connections from any IP address locally. The server then performs the initial steps related to passive opening: establishing a socket, binding it to a local address, and then setting the maximum number of simultaneous connections allowed. Finally, the main loop waits for the remote host to attempt to connect to it, and when a remote host tries to connect to it, it receives and outputs the characters sent from the connection.

Iv. Report of the experiment

1. Describe the experimental process in detail.

2. Implementation of 1 data communication transmission

The experiment is carried out under Fedora Linux, which realizes a simple socket communication process: the client establishes the socket to send the message to the specified server, the server listens to the socket, and prints the message when it is received.

First write the client code as follows:

/*************************************************************** * Client program *author:duancong *DATE:2012/11/3 ********* /#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include < netinet/in.h> #include <netdb.h>//one row of maximum bytes #define Maxline 4096 int main (int argc, char** argv) {int sock
    FD, N; Char recvline[4096], sendline[4096];//send and accept row array struct sockaddr_in servaddr;//parameter struct hostent record host letter
    The structure of the interest/determine whether the input parameter if (ARGC!= 2) {//is prompted to use the method printf when entering the host name as a parameter ("use method:./client  


The server-side program is as follows:

/******************************************************************** * Server-side program *author:duancong *DATE:2012/11/3 * * * * * * * * /#include <stdio.h> #include <stdlib.h > #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #
    include<netinet/in.h> #include <unistd.h>//Maximum number of bytes received #define maxline 4096 int main (int argc, char** argv) {
    int LISTENFD, CONNFD;
    struct sockaddr_in servaddr;
    Char buff[4096];
    int n; Create a socket for listening ((LISTENFD = socket (af_inet, sock_stream, 0) = = 1) {//Create failure printf ("Create socket Error:%s" (Error number:%d
    ) \ n ", Strerror (errno), errno);
    Exit (0);
    }//empty address structure memset (&servaddr, 0, sizeof (SERVADDR)); Configure the address family and port number servaddr.sin_family = af_inet;//address Family servaddr.sin_addr.s_addr = htonl (inaddr_any);//IP not named to accept any IP address Connection Servaddr.sin_port = htons (5432);//port number//BIND socket to local address if (binD (LISTENFD, (struct sockaddr*) &servaddr, sizeof (servaddr)) = = 1) {//bind failed printf ("Bound Socket Error:%s (Error number:%d) \ n", stre
    Rror (errno), errno);
    Exit (0); ///Listen port and set maximum number of if (Listen (LISTENFD, 10) = = 1) {//Listen for failure printf ("Listen socket Error:%s (Error number:%d) \ n", Strerror (errno
    ), errno);
    Exit (0);
    //prompts to start waiting for client request printf ("= = = Wait for client request ======\n");
        Start waiting for request and receive while (1) {if (CONNFD = Accept (LISTENFD, (struct sockaddr*) null, NULL) = = 1) {//Receive error, Loop continues
        printf ("Receive request Error:%s (Error number:%d)", Strerror (errno), errno);
    Continue
    }//Receive data N = recv (CONNFD, Buff, maxline, 0);
    Buff[n] = ' yes ';//Add string terminator//print out received message printf ("received message from client:%s", buff);
    Closes the socket connection close (CONNFD);
Close (LISTENFD); }


Then compile using the GCC 4.6.3:

GCC client.c-o client 
gcc server.c-o server

Compilation completed generates two executable files for client and server.

Run server-side programs first

Run the client program again, before running, first view the local host name:

You can see that the host name is Localhost.localdomain

Continue to run client, take the host name you see above as a parameter, and enter the message you want to send

After the message is sent, the socket closes automatically and the server receives the message

Continue to send a few messages, the server side also displayed





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.