Linux programming basics-Socket programming

Source: Internet
Author: User

Socket programming in Linux generally includes Tcp Socket, Udp Socket, or Raw Socket. Socket programming in TCP and UDP mode is used to compile socket programs at the application layer, we use a lot of data, while Raw Socket is rarely used, which is not included in the scope of this article.

TCP Socket

The general process of TCP-based client/server programs is as follows:

It can basically be divided into three parts:

1. Establish a connection:

  1. After the server calls socket (), bind (), and listen () to complete initialization, it calls accept () to block the wait and is in the status of the listening port.
  2. After the client calls socket () initialization, connect () is called to send SYN segments and block requests waiting for the server to respond.
  3. The server responds to an SYN-ACK segment, the client returns from connect () after receiving it, and an ACK segment at the same time, the server returns from accept () after receiving it.

Ii. data transmission:

After the connection is established, the TCP protocol provides a full-duplex communication pipeline. The server and client can transmit data through repeated calls of read and write based on the protocol.

3. Close the connection:

After data transmission is complete, the server and client can call Close to Close the connection. After one end closes the connection, the read function of the other end returns 0, this feature can be used to sense the exit of the other end.

The following uses a simple EchoServer to demonstrate how to create the server and client code. Both the code and the socket-related APIs are highlighted.

Server example:

# Include <stdio. h>
# Include
<Stdlib. h>
# Include
<String. h>
# Include
<Unistd. h>
# Include
<Sys/socket. h>
# Include
<Netinet/in. h>
# Include
<Arpa/inet. h>

# Define MAXLINE 80
# Define SERV_PORT 8000

Int main (void)
{
Char buf [MAXLINE];

Int listenfd = 0;
Listenfd = socket (AF_INET, SOCK_STREAM, 0 );

Sockaddr_in servaddr = {0 };
Servaddr. sin_family = AF_INET;
Servaddr. sin_addr.s_addr = htonl (INADDR_ANY );
Servaddr. sin_port = htons (SERV_PORT );

Bind (listenfd, (sockaddr *) & servaddr, sizeof (servaddr ));
Listen (listenfd, 20 );

Printf ("Accepting connections... \ n ");
While (1)
{
Sockaddr_in cliaddr = {0 };
Socklen_t cliaddr_len = sizeof (cliaddr );
Int connfd = accept (listenfd, (sockaddr *) & cliaddr, & cliaddr_len );

Char str [INET_ADDRSTRLEN];
Printf ("connected from % s at PORT % d \ n ",
Inet_ntop (AF_INET, & cliaddr. sin_addr, str, sizeof (str )),
Ntohs (cliaddr. sin_port ));

While (true)
{
Int count = read (connfd, buf, MAXLINE );
If (count = 0)
Break;

Write (connfd, buf, count );
}

Close (connfd );
Printf ("closed from % s at PORT % d \ n ",
Inet_ntop (AF_INET, & cliaddr. sin_addr, str, sizeof (str )),
Ntohs (cliaddr. sin_port ));
}
}

PS: note that the second sock function parameter SOCK_STREAM indicates a TCP connection. We will introduce how to open a udp connection through SOCK_DGRAM.

The main process on the server side is an endless loop. It accepts a socket connection and returns it to the client intact. After the client exits, it closes the socket connection and accepts the next socket connection again.

The client code is as follows:

# Include
<Stdio. h>
# Include
<Arpa/inet. h>
# Include
<Stdlib. h>
# Include
<Unistd. h>
# Include
<Sys/socket. h>
# Include
<Netinet/in. h>

# Define MAXLINE 80
# Define SERV_PORT 8000
# Define MESSAGE "hello world"

Int main (int argc, char * argv [])
{
Char buf [MAXLINE];

Int sockfd = socket (AF_INET, SOCK_STREAM, 0 );

Sockaddr_in servaddr = {0 };
Servaddr. sin_family = AF_INET;
Inet_ton (AF_INET, "127.0.0.1", & servaddr. sin_addr );
Servaddr. sin_port = htons (SERV_PORT );

If (0! = Connect (sockfd, (sockaddr *) & servaddr, sizeof (servaddr )))
{
Printf ("connected failed ");
Return 1;
}

Write (sockfd, MESSAGE, sizeof (MESSAGE ));
Int count = read (sockfd, buf, MAXLINE );

Printf ("Response from server: % s \ n", buf );

Close (sockfd );
Return 0;
}

The client code is relatively simple. I will not introduce it here.

UDP Socket

Shows the typical UDP client/server communication process:

Because UDP does not need to maintain connections, the program logic is much simpler, but the UDP protocol is unreliable. In fact, there are many mechanisms to ensure communication reliability at the application layer, more code may be needed.

A typical example is as follows:

/* Server. cpp */
# Include
<Stdio. h>
# Include
<String. h>
# Include
<Netinet/in. h>
# Include
<Arpa/inet. h>

# Define MAXLINE 80
# Define SERV_PORT 8000

Int main (void)
{
Char buf [MAXLINE];
Char str [INET_ADDRSTRLEN];

Int sockfd = socket (AF_INET, SOCK_DGRAM, 0 );

Sockaddr_in servaddr = {0 };
Servaddr. sin_family = AF_INET;
Servaddr. sin_addr.s_addr = htonl (INADDR_ANY );
Servaddr. sin_port = htons (SERV_PORT );

Bind (sockfd, (sockaddr *) & servaddr, sizeof (servaddr ));

Printf ("Accepting connections... \ n ");
While (1)
{
Sockaddr_in cliaddr;
Socklen_t cliaddr_len = sizeof (cliaddr );

Int count = recvfrom (sockfd, buf, MAXLINE, 0, (sockaddr *) & cliaddr, & cliaddr_len );
If (count <0)
{
Printf ("recvfrom error ");
Continue;
}

Printf ("received from % s at PORT % d \ n ",
Inet_ntop (AF_INET, & cliaddr. sin_addr, str, sizeof (str )),
Ntohs (cliaddr. sin_port ));

Sendto (sockfd, buf, count, 0, (sockaddr *) & cliaddr, sizeof (cliaddr ));
}
}

/* Client. cpp */
# Include
<Stdio. h>
# Include
<String. h>
# Include
<Unistd. h>
# Include
<Netinet/in. h>
# Include
<Arpa/inet. h>

# Define MAXLINE 80
# Define SERV_PORT 8000

Int main (int argc, char * argv [])
{
Char buf [MAXLINE];
Char str [INET_ADDRSTRLEN];

Int sockfd = socket (AF_INET, SOCK_DGRAM, 0 );

Sockaddr_in servaddr = {0 };
Servaddr. sin_family = AF_INET;
Inet_ton (AF_INET, "127.0.0.1", & servaddr. sin_addr );
Servaddr. sin_port = htons (SERV_PORT );

While (fgets (buf, MAXLINE, stdin )! = NULL)
{
Int count = sendto (sockfd, buf, strlen (buf), 0, (sockaddr *) & servaddr, sizeof (servaddr ));
If (count =-1)
{
Printf ("sendto error ");
Return 0;
}

Count = recvfrom (sockfd, buf, MAXLINE, 0, NULL, 0 );
If (count =-1)
{
Printf ("recvfrom error ");
Return 0;
}

Write (STDOUT_FILENO, buf, count );
}

Close (sockfd );
Return 0;
}

 

 

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.