General steps for Linux Network programming (1)

Source: Internet
Author: User
Tags htons

One, the address structure of the socket.

The IPV4 socket address structure is also commonly referred to as the "internetwork socket address Structure", which is sockaddr_in

Named POSIX is defined as follows:

#include <stdio.h>structin_addr{unsignedLongS_ADDR;/*32-bit IPv4 Address network byte ordered*/};/*SOCKETADDR structures are generally used as parameters to specify address information*/structsockaddr{unsigned Shortsa_family;/*Address Family,af_xxx*/    Charsa_data[ -];/*14bytes of protocol address*/};/*sa_family is the address family, which is generally the form of "af_xxx".*//*Sa_data is a 14-byte protocol address. Sockaddr This struct does not act as an object but as a parameter to the BIND,CONNECT,RECVFROM,SENDTO function, indicating the address information.*/structsockaddr_in{ Shortsockaddr_in;/*Address Family*/unsigned ShortSin_port;/*Port Number*/    structIN_ADDR sin_addr;/*Internet Address*/unsignedCharsin_zero[8];/*same size as struct sockaddr*/};/*sin_family Specifies the protocol family, which can only be af_inet in socket programming.   The Sin_port storage port number (typically and htons with the network byte order) sin_addr stores the IP address, using the IN_ADDR data structure. Sin_zero is an empty byte reserved for Sockadr and sockaddr_in two data structures to remain the same size. */intMainvoid){    /*the size is the same.*/printf ("sizeof (sockaddr_in) =%d,sizeof (sockaddr) =%d\n",            sizeof(structSOCKADDR_IN),sizeof(structsockaddr)); return 0;}

1. Conversion functions between host byte order and network byte order

unsigned short htons (unsigned short host16bit);

unsigned long htonl (unsigned long host32bit); Returns the value of the network byte order.

unsigned short ntohs (unsigned short net16bit);

unsigned long ntohl (unsigned long net32bit);

Returns the value of the host byte order.

H represents Host,n on behalf of Network,s on behalf of Short,l long.

2. Byte manipulation functions

#include <strings.h>

void Bzero (void* dest,size_t nbytes);

void bcopy (const void* src,void* dest,size_t nbytes);

int bcmp (const void* ptrl,const void* ptr2,size_t nbytes);

Bzero The specified number of bytes in the target byte string to 0. We often use this function to

A socket address structure is initialized to 0.

Bcopy moves the bytes of the specified data from the source byte string to the destination byte string.

BCMP compares two arbitrary byte strings, returns 0 if the same, otherwise returns to non 0.

ANSI C functions

#include <string.h>

void* memset (void* dest,int c,size_t len);

void* memcpy (void* dest,const void* src,size_t nbytes);

int memcmp (const void* ptr1,const void* ptr2,size_t nbytes);

Memset the byte of the target specified data to a value c,memcpy similar to bcopy

However, the order of the two pointer parameters is reversed.

When the source byte string overlaps with the target byte string, the bcopy can be handled correctly, but

The memcpy operation result is unknown. You must use ANSI C for this scenario

Under the Memmove.

3. Address conversion function

int Inet_aton (const char* strptr,struct in_addr* addrptr);

Returns 1 if the string is valid, otherwise 0;

Converts the C string referred to by StrPtr to a 32-bit network byte-order binary,

and stored by the pointer addrptr. If the successful return 1, failure 0

char* inet_ntoa (struct in_addr inaddr);

A pointer to a dotted decimal number string.

in_addr_t inet_addr (const char* strptr);

If the string is valid, the IPV4 address of the 32-bit binary network byte order,

Otherwise, it is inaddr_none;

char* inet_ntoa (struct in_addr inaddr);

Returns a pointer to a dotted decimal string.

Convert the address between addresses to a more uniform function:

#include <arpa/inet.h>

int Inet_pton (int family,const char* strptr,void* addrptr);

If 1 is returned successfully, 0 is returned if the input is not a valid expression, and an error returns-1.

Const char* inet_ntop (int family,const void* addrptr,char* srptr,size_t len);

If successful, a pointer to the result, or null if an error occurs.

Second, basic TCP socket programming.

1. Create a socket descriptor.

int socket (int family,int type,int protocol);

A non-negative descriptor if successful, or 1 if there is an error.

The family parameter indicates the protocol family, Af_inet,af_local,af_inet6

The type refers to the byte order, which is typically the sock_stream data stream, and the Sock_dgream datagram.

Sock_seqpacket an ordered packet socket, sock_raw the original socket.

Protocol IPPROTO_CP TCP Transport protocol

IPPROTO_UDP UDP Transport Protocol

IPPROTO_SCTP SCTP Transfer Protocol

2.TCP customer uses the Connect function to establish a connection to the TCP server.

int connect (int sockfd,const struct sockaddr* servaddr,socklen_t addrlen);

If 0 is returned successfully, return-1 if there is an error.

SOCKFD is the socket descriptor returned by the socket function, and the second third parameter

Is the pointer to the address structure of the execution socket and the size of the pointer, respectively.

The client does not have to call the BIND function before calling the function connect, because, if necessary,

The kernel determines the source IP address and selects a temporary port as the source port.

If it is a TCP socket, calling the Connect function will fire the three-way TCP

Handshake, and returns only if the connection is successful or error-

TCP state transition diagram, the Connect function causes the current socket from the closed state

(The socket is in the same state as it was created by the socket function) to

Syn_sent status, if successful, then transfer to established state.

3.int bind (int sockfd,const struct sockaddr* myaddr,socklen_t addrlen);

The second parameter is a pointer to the protocol-specific address structure, and the third parameter is the length of the address structure.

Typically used for the server to bind the address and port, if a TCP client or server

Bind a port has not been called, when Connect or Linsten is called, the kernel will

Socket to select a temporary port.

4.int Listen (int sockfd,int backlog);

The Listen function is only called by the TCP server, and it does two things.

A. When the socket function creates a socket, it is assumed to be an active socket, i.e.,

It is a client socket that will invoke connect to initiate a connection. The Listen function converts an unbound socket

into a passive socket that indicates that the kernel should receive a connection request to execute the socket. Based on the TCP state graph, call

Listen causes the socket to transition from the closed state to the listen state.

B. The second parameter of this function specifies the maximum number of connections that the kernel should queue for the corresponding socket.

Successful return 0, Failure returns-1.

The 5.accept function is called by the TCP server to return the next completed connection from the queue header that has completed the connection.

If the completed connection queue is empty, then the process is put to sleep (assuming the socket is the default blocking mode)

int accept (int sockfd,struct sockaddr* cliaddr,socklen_t* addrlen);

Cliaddr and Addrlen are used to return the protocol address of the peer process (customer) that is already connected. Addrlen is a value-result parameter

A non-negative descriptor was returned successfully, and an error returned-1.

If the accept succeeds, the return value is a completely new descriptor that is automatically generated by the kernel, representing the

TCP connections. When we discuss the Accept function, we call its first parameter a listening socket descriptor, which is called its return

The value is a socket descriptor that is already connected. A server typically creates only one listener socket, which

Lifetime. The kernel creates a connected socket for each client connection received by the server process

The word. When the server finishes servicing a given customer, the corresponding connected sockets are closed.

6.fork () function

pid_t fork (void);

In the child process is 0, the process ID is in the parent process, and an error returns-1.

Function-specific:

The function is called once and returns two times.

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.