Establish a TCP connection using C language socket function in Linux

Source: Internet
Author: User
Tags htons

This article describes how to use the C language socket function in Linux to establish a TCP connection, which is compatible with C ++.

TCP connections can be used to transmit information of common protocols such as HTTP and FTP, which is an important part of Linux network programming.

Header file to be referenced
For network programming, you usually need to reference the following header file

# Include <sys/socket. h>
# Include <sys/types. h>
# Include <netinet/in. h>
# Include <ARPA/inet. h>
# Include <netdb. h>
# Include <unistd. h>
 
// The following header file is used to make the sample program run normally.
# Include <string. h>
# Include <stdio. h>
# Include <stdlib. h>

Client Program

Struct sockaddr_in pin;
Struct hostent * nlp_host;
Int SD;
Char host_name [2, 256];
Int port;
 
// Initialize the host name and port. The host name can be an IP address or a Resolved Name.
Strcpy (host_name, "www.linux-wiki.cn ");
Port = 80;
 
// Resolve the domain name. If it is an IP address, no resolution is required. If an error occurs, an error message is displayed.
While (nlp_host = gethostbyname (host_name) = 0 ){
Printf ("resolve error! \ N ");
}
 
 
// Set the pin variable, including the protocol, address, and port. This segment can be directly copied to your program.
Bzero (& pin, sizeof (PIN ));
Pin. sin_family = af_inet; // af_inet indicates that IPv4 is used.
Pin. sin_addr.s_addr = htonl (inaddr_any );
Pin. sin_addr.s_addr = (struct in_addr *) (nlp_host-> h_addr)-> s_addr;
Pin. sin_port = htons (port );
 
// Create a socket
SD = socket (af_inet, sock_stream, 0 );
 
// Establish a connection
While (connect (SD, (struct sockaddr *) & pin, sizeof (PIN) =-1 ){
Printf ("Connect error! \ N ");
}

Now, the connection to the server has been established. For the communication method, see the last part.

Server programs
This section is C ++ code.

Int serversocket;
Struct sockaddr_in serveraddr;
Struct sockaddr_in clientaddr;
 
// Port used for saving
Int Port = 8000;
 
// Create a socket and set
Serversocket = socket (af_inet, sock_stream, 0 );
 
// Set the socket option. This is optional and prevents the server program from running again quickly.
Int val = 1;
Setsockopt (serversocket, sol_socket, so_reuseaddr, & Val, sizeof (VAL ));
 
// Define the port and listening address
Serveraddr. sin_family = af_inet;
Serveraddr. sin_port = htons (port );
Serveraddr. sin_addr.s_addr = htonl (inaddr_any );
Memset (& (serveraddr. sin_zero), 0, 8 );
Int rc = BIND (serversocket, (struct sockaddr *) & serveraddr,
Sizeof (struct sockaddr ));
If (rc =-1 ){
Printf ("Bad bind \ n ");
Exit (1 );
}
 
// Enable the serversocket listener. The client queue length is 5.
Rc = listen (serversocket, 5 );
If (rc =-1 ){
Printf ("Bad listen \ n ");
Exit (1 );
}
 
// Wait for the customer to connect
Int sock;
Int clientaddrsize = sizeof (struct sockaddr_in );
Sock = accept (serversocket,
(Struct sockaddr *) & clientaddr,
(Socklen_t *) & clientaddrsize );

In this way, the connection has been established, and the returned sock is a new socket that can be used for communication.

Communication Method
Send information
Send (int sd, char * data, int Len, 0 );
Where SD is the socket variable name (file descriptor), data is the address of the data buffer, Len is the size of the buffer, and 0 usually does not need to be changed

Receive information
Recv (int sd, char * Buf, int maxlen, 0 );
Close connection
Close (int sd );

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.