Linux C socket programming-connection-oriented instance

Source: Internet
Author: User
Tags htons
Connection-oriented socket instance

CodeThe server in the instance sends the string "Hello, you are connected!" to the client through a socket connection !". If you run the software on the server and the client runs the software on the client, the client receives the string.

Server code:

# Include

# Include

# Include

# Include

# Include

# Include

# Include

# Include

/* Server listening port number */

# Define servport 3333

/* Maximum number of simultaneous connection requests */

# Define backlog 10

Main (){

/* Sock_fd: Listener socket; client_fd: Data Transmission socket */

Int sockfd, client_fd;

/* Local address information */

Struct sockaddr_in my_addr;

/* Client address information */

Struct sockaddr_in remote_addr;

If (sockfd = socket (af_inet, sock_stream, 0) =-1 ){

Perror ("socket creation error! "); Exit (1 );

}

My_addr.sin_family = af_inet;

My_addr.sin_port = htons (servport );

My_addr.sin_addr.s_addr = inaddr_any;

Bzero (& (my_addr.sin_zero), 8 );

If (BIND (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr) =-1 ){

Perror ("BIND error! ");

Exit (1 );

}

If (Listen (sockfd, backlog) =-1 ){

Perror ("listen error! ");

Exit (1 );

}

While (1 ){

Sin_size = sizeof (struct sockaddr_in );

If (client_fd = accept (sockfd, (struct sockaddr *) & remote_addr, & sin_size) =-1 ){

Perror ("Accept error");

Continue;

}

Printf ("received a connection from % Sn", inet_ntoa (remote_addr.sin_addr ));

/* Sub-process code segment */

If (! Fork ()){

If (send (client_fd, "Hello, you are connected! N ", 26, 0) =-1)

Error ("send error! ");

Close (client_fd );

Exit (0 );

}

Close (client_fd );

}

}

The workflow of the server is as follows: first call the socket function to create a socket, and then call the BIND function to bind it to the local address and a local port number, then, call listen to listen on the corresponding socket. When accpet receives a connection service request, a new socket is generated. The server displays the IP address of the client and sends the string "Hello, you are connected!" to the client through the new socket !". Close the socket.

The fork () function in the Code instance generates a sub-process to process the data transmission part. The value returned by the fork () Statement for the sub-process is 0. Therefore, the IF statement containing the fork function is the sub-process code part, and it is executed concurrently with the parent Process Code part after the if statement.

ClientProgramThe Code is as follows:

# Include

# Include

# Include

# Include

# Include

# Include

# Include

# Include

# Define servport 3333

# Define maxdatasize 100/* maximum data transmission volume each time */

Main (INT argc, char * argv []) {

Int sockfd, recvbytes;

Char Buf [maxdatasize];

Struct hostent * Host;

Struct sockaddr_in serv_addr;

If (argc
Fprintf (stderr, "Please enter the server's hostname! N ");

Exit (1 );

}

If (host = gethostbyname (argv [1]) = NULL ){

Herror ("gethostbyname error! ");

Exit (1 );

}

If (sockfd = socket (af_inet, sock_stream, 0) =-1 ){

Perror ("socket creation error! ");

Exit (1 );

}

Serv_addr.sin_family = af_inet;

Serv_addr.sin_port = htons (servport );

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 );

}

If (recvbytes = Recv (sockfd, Buf, maxdatasize, 0) =-1 ){

Perror ("Recv error! ");

Exit (1 );

}

Buf [recvbytes] = '0 ′;

Printf ("received: % s", Buf );

Close (sockfd );

}

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.

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.