Linux C socket development and compilation example

Source: Internet
Author: User
Tags socket error htons

This log is based on an example that can run successfully. Once the program runs successfully, I want to ask why? It seems that this is easier to understand and grasp.

I won't write more about the concept of the socket program here, but I believe that if I can read this entire article, I believe there will be no such questions.

The following is a C/S program. The main function is that the client will send some messages to the server. When the server receives a request from the client, it will send a response message to the client.

The server. C code is as follows:

# Include <stdio. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>
# Include <sys/types. h>
# Include <netinet/in. h>
# Include <sys/socket. h>
# Include <sys/Wait. H>
 
# Define servport 3333
# Define backlog 10
# Define Max size 1024
 
Int main (){
Int sockfd, client_fd;
Struct sockaddr_in my_addr;
Struct sockaddr_in remote_addr;
// Create a socket
If (sockfd = socket (af_inet, sock_stream, 0) =-1 ){
Perror ("socket create failed! ");
Exit (1 );
}
 
// Bind the port address
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 );
}
 
// Listening port
If (Listen (sockfd, backlog) =-1 ){
Perror ("Listen error ");
Exit (1 );
}
 
While (1 ){
Int 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 % s/n", (char *) inet_ntoa (remote_addr.sin_addr ));
 
// Sub-process segment
If (! Fork ()){
// Receive request information sent by the client
Int rval;
Char Buf [maxsize];
If (rval = read (client_fd, Buf, maxsize) <0 ){
Perror ("reading stream error! ");
Continue;
}
Printf ("% s/n", Buf );
 
// Send information to the client
Char * MSG = "Hello, Mr hqlong, you are connected! /N ";
If (send (client_fd, MSG, strlen (MSG), 0) =-1) perror ("send error! ");
Close (client_fd );
Exit (0 );
}
Close (client_fd );
}
Return 0;
}

Compile and start the service

Hqlong @ Ubuntu :~ $ GCC server. C-O Server
Hqlong @ Ubuntu :~ $./Server &

Here, our server is running as a service backend. If you want to know the running status of the background service, you may use netstat to view it.

Hqlong @ Ubuntu :~ // T $ netstat-nl | grep 3333
TCP 0 0 0.0.0.0: 3333 0.0.0.0: * listen

It can be seen that port 3333 is already listening, which indicates that the service has been started.
To test whether the server can accept client requests, Telnet can be used for testing.

Hqlong @ Ubuntu :~ $ Telnet 127.0.0.1 3333
Trying 127.0.0.1...
Received a connection from 127.0.0.1
Connected to 127.0.0.1.
Escape Character is '^]'.
Test
Test
 
Hello, Mr hqlong, you are connected!
Connection closed by foreign host.

We can see that we use Telnet to connect to the server just started, and then send a message "test" to the server. After the server receives this message, A response message is sent to the client, telling us that we are connected.

Next, write your own client program. The complete function is the same as the Telnet test function above. Send a message to the server. After receiving this message, the server sends a Response Message to the client.
The Code is as follows: client. c

# Include <stdio. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>
# Include <sys/types. h>
# Include <netinet/in. h>
# Include <sys/socket. h>
# Include <sys/Wait. H>
 
# Define servport 3333
# Define maxdatasalize 100
# Define server_ip "127.0.0.1"
# Define data "this is a client message"
 
Int main (INT argc, char * argv []) {
Int sockfd, recvbytes;
Char Buf [maxdatasize];
Struct hostent * Host;
Struct sockaddr_in serv_addr;
 
If (sockfd = socket (af_inet, sock_stream, 0) =-1 ){
Perror ("socket error! ");
Exit (1 );
}
Bzero (& serv_addr, sizeof (serv_addr ));
Serv_addr.sin_family = af_inet;
Serv_addr.sin_port = htons (servport );
Serv_addr.sin_addr.s_addr = inet_addr (server_ip );
 
If (connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (struct sockaddr) =-1 ){
Perror ("Connect error! ");
Exit (1 );
}
 
Write (sockfd, Data, sizeof (data ));
If (recvbytes = Recv (sockfd, Buf, maxdatasize, 0) =-1 ){
Perror ("Recv error! ");
Exit (1 );
}
 
Buf [recvbytes] = '/0 ';
Printf ("Received: % s", Buf );
Close (sockfd );
Return 0;
}

Compile and run

Hqlong @ Ubuntu :~ $ GCC client. C-O client
Hqlong @ Ubuntu :~ $./Client
Received a connection from 127.0.0.1
Hello, Mr hqlong, you are connected!
Connection closed by foreign host.

The above is the compilation of the entire server and client program.


Shows the typical Socket System Call performed by the program when the connection-oriented protocol (TCP) is used. The server program establishes a socket and calls the BIND function to associate the socket with the local protocol port, then, the listen and accept functions are used to place the socket parameter in the passive listening mode and receive the connection.
The customer program also establishes a socket, and then calls the connect function to start the network conversation. After a connection is established between the client and the server, you can use functions such as read and write to communicate with each other.
For more information about functions, see the Linux C function manual.

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.