Linux Network Programming 3--socket

Source: Internet
Author: User
Tags function prototype

Macro definition

First introduce two macro definitions, see the following code

Code 1
/************************************************************************* > File name:test.c > Author: Krischou > Mail:[email protected] > Created time:thu 10:11:59 AM CST ******************************* *****************************************/#include<stdio.h>#define__JOIN__ (post_fix) tag_# #post_fixtypedefintTag_element;typedefinttag_arr[Ten];intMainintargcChar*argv[])     {__join__ (element) Val1;    __JOIN__ (arr) val2; intindex;  for(index =0; Index <9; index++) {Val2[index]= index +1; printf ("%3d", Val2[index]); } printf ("\ n"); return 0;}

Operation Result:

08280828]$./a. Out  1  2  3  4   5  6  7)  8  9

Take a look at the pre-treated code

typedefintTag_element;typedefinttag_arr[Ten];intMainintargcChar*argv[])    {tag_element val1;   Tag_arr Val2; intindex;  for(index =0; Index <9; index++) {Val2[index]= index +1; printf ("%3d", Val2[index]); } printf ("\ n"); return 0;}

That is, the macro definition #define __join__ (post_fix) tag_# #post_fix connect the tag_ with the parameter Post_fix

Example

Observe a parameter of struct struct sockaddr_in, previously defined as follows:

#define __sockaddr_common (sa_prefix) sa_family_t sa_prefix# #family
Then there are:
__sockaddr_common (sin_);     -     sa_family_t sin_family
Code 2
<stdio.h>#define STR (s) #s//#define IP 192.168.1.1int main (int Char *argv[]) {    char buf[] = STR (helloworld!);    printf ("%s \ n", buf)    ; return 0 ;}

Run results

08280828]$./a. OutHelloWorld!
Summary

We use # To change the macro argument to a string with # #把两个宏参数贴合在一起.

Using the TCP protocol server side

1. Header files

#include <sys/types.h><sys/socket.h><netinet/in .h>< arpa/inet.h><unistd.h><string.h><stdio.h>  <stdlib.h>

2. Socket function: Generates a set of interface descriptors.

int socket ( int domain,int type,int  protocol);
Parameters: Domain?af_inet:ipv4 network protocol; Af_inet6:ipv6 Network protocol. Type Tcp:sock_stream;Udp:sock_dgram. Protocol? Specifies the transport protocol number used by the socket. is usually 0. 
 
  
return Value: Success returns a set of interface descriptors, failure returns -1.

3. Bind function: Used to bind a port number and IP address, so that the socket interface with the specified port number and IP address associated.

Prototype:int bind (int sockfd,struct sockaddr * my_addr,int addrlen);

parameter: SOCKFD is the return value of the preceding socket. MY_ADDR is the structure body length of the struct pointer variable Addrlen to SOCKADDR. is usually calculated sizeof (struct sockaddr)

return Value: Success returns 0, failure returns -1

A common data structure is defined for different socket domain, as follows. Note that this SOCKADDR structure will have different structure definitions depending on the different socket domain used.
struct sockaddr  // This struct is not commonly used {    shortint sa_family;  // the domain parameter when the socket () is called, which is the af_inet value.      Char sa_data[];              // use a maximum of 14 character lengths };

For example, using Af_inet domain, its SOCKETADDR structure is defined as follows:

struct sockaddr_in  // common struct {    shortint sin_family;  // that is sa_family? af_inet    uint16_t Sin_port;              // the port number to use     struct in_addr sin_addr;        // for the IP address     Char sin_zero[8];      // not used };

Where thestruct in_addr is:

struct in_addr{    uint32_t s_addr;};

4. Listen function: Make this port and IP of the server in listening state, waiting for the connection request of a client in the network. If the client has a connection request, the port accepts the connection.

Prototype:int Listen (int sockfd,int  backlog);
 
  
Parameter: SOCKFD is the return value of the preceding socket, which is SFD. The backlog specifies the maximum connection requirements that can be processed at the same time, typically 10 or 5, and the maximum value can be set to 128.
 
  
return Value: Success returns 0, failure returns -1

5. Accept function: Accepts a connection request from a remote computer and establishes a communication connection with the client. When the server is listening, if the client's connection request is received at some point, the request is not processed immediately, but the request is placed in the waiting queue and the client's connection request is processed when the system is idle. When the Accept function accepts a connection, a new socket identifier is returned, and subsequent data transfers and reads are processed by the new socket number, and the socket in the original parameter can continue to be used to listen to other client connection requests. (that is, similar to the mobile business, if a customer calls 10086, the server will request a connection, processing some transactions, notify an operator to answer the customer's call, that is, all the subsequent operations, at this time has no relationship with the server, but the operator and the customer's communication. corresponding to the customer request to connect our server, our server did some binding and listening and so on, if the connection is allowed, then call the Accept function to generate a new socket, and then use this new socket with our customers to send and receive data. That is, the server has a successful connection with a client, and there are two sockets. )

Prototype:int Accept (int s,struct sockaddr * addr,int * addrlen);
 
  
parameter: S is the return value of the preceding socket, which is SFD.  addr is a struct pointer variable, and the struct of bind is the same type, the system will store the remote host's information (the remote host's address and port number information) to this pointer refers to the structure of the body. Addrlen represents the length of the struct, which is an integer pointer.    
 
  
return Value: Success returns a new socket descriptor for communicating with the client. Failed return -1

6. recv function: Use the new socket to receive data from the remote host and save the data to the memory space pointed by the parameter buf.

Prototype:int recv (int sockfd,void *buf,intint  flags);
 
  
Parameter: SOCKFD is the return value of the preceding accept, that is, NEW_FD, which is the new socket. The BUF represents a buffer. Len indicates the length of the buffer. The flags are usually 0.
 
  
return Value: Success returns the actual number of characters received, which may be less than the receive length you specify. Failed to return -1. 

7. Send function: Sends data to the specified remote host with a new socket.

Prototype:int send (int s,constvoid * msg,intint  flags);
 
  
Parameter: S is the return value of the front accept, which is new_fd. MSG is generally a constant string. Len represents the length. The flags are usually 0.
 
  
return Value: Success returns the actual number of characters sent, which may be less than the send length you specified. Failed to return -1. 

8. Close function: When you are finished using the file, you can close the file by using close () if it is no longer needed, and close () causes the data to be written back to disk and frees the resources that the file occupies.

Prototype:int close (int  FD);
 
  
return value: Returns 0 if the file is closed successfully and returns 1 if an error occurs . 
Summary

1. The Listen function makes the active connection socket interface A passive connection socket interface, allowing a process to accept requests from other processes to become a server process. In TCP server programming, the Listen function transforms a process into a server and specifies that the corresponding socket becomes a passive connection. The listen function is called before calling accept after calling bind, and its function prototype is as follows:

int listen (intInt. Backlog)

2. The socket function returns the socket FD, the default is an active connection socket, that is, the system assumes that the user will call the Connect function on the socket, expect it to actively connect with other processes, and then in the server programming, the user wants this socket can accept foreign connection request, That is, passively waiting for the user to connect. Since the system defaults to a socket that is actively connected, there is a way to tell the system that the user process is doing it through the listen function.

3. When the server process processes the connection request, there may be other connection requests at the same time. The kernel maintains a queue (client connection request queue) in its own process space to hold the contact information (port number and IP) of the connection request that the server is listening to.

4. The service program calls the Accept function to remove the first customer request from the Client connection request queue of a stream socket in the listening state, and creates a new socket to create a connection channel with the client socket, and if the connection succeeds, returns the descriptor of the newly created socket. The newly created socket is later exchanged for the data with the client socket, and if it fails, returns Invalid_socket. The first parameter of the function specifies a stream socket in the listening state; the operating system uses the second parameter to return the address structure of the newly created socket, and the operating system uses the third parameter to return the length of the address structure of the newly created socket.

Client

Connect function: Used to request a connection to a remote server, connect the socket of the parameter SOCKFD to the server IP and port number specified in the parameter serv_addr.

Prototype:int connect (int sockfd,struct sockaddr * serv_addr,int  addrlen);
 
  
Parameter: SOCKFD is the return value of the preceding socket, which is SFD. SERV_ADDR is a struct pointer variable that stores the IP and port number information for a remote server. Addrlen represents the length of a struct variable.
 
  
return Value: Success returns 0, failure returns -1. 

Linux Network Programming 3--socket

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.