Introduction to programming of network programming sockets

Source: Internet
Author: User
Tags posix

This section describes sockets that enable remote interprocess communication between different computers. Socket interface is the ID of the network process, in the network each node has a network address, that is, IP address, two inter-process communication, the first to determine the network address of the respective network node. However, as long as the network address determines the computer on which the process resides, because there may be multiple network processes on a single computer, the network address alone is not sure which process is in the network, so additional information is needed in the socket, which is the port. On a single computer, a port number can be assigned to only one process, so there is a one by one relationship between the process and the port. Therefore, using a combination of port numbers and network addresses uniquely identifies a network process across the network.

Socket address Structure

The network address and port number information used in the network application is placed in a structure, that is, the socket interface address structure. Most of the socket functions require a pointer to the address structure of the socket to be used as a parameter to pass the address information. Each protocol family defines its own set of interface address structures, which begin with sockaddr_ and end with two letters in each of the Protocol's names.

/* Introduction to Socket Programming *//* Universal Socket address structure *//* defined in the <sys/socket.h> header file */struct sockaddr{uint8_t Sa_len;  sa_family_t sa_family; /* Address family:af_xxx value */char sa_data[14];/* protocol-specific Address */};/* * Description: * When the socket address is passed as a parameter into any What socket function, the socket address structure is always passed as a reference (that is, a pointer to the structure); * Therefore, the socket address structure of a specific protocol domain must be cast to a generic socket address structure type; *//* IPv4 socket address structure *//* defined in <netinet /in.h> header file */struct in_addr{in_addr_t s_addr;/* 32-bit IPV4 Address */* network byte o    rdered */};struct sockaddr_in{uint8_t Sin_len; /* Length of struct (+) */sa_family_t sin_family;   /* af_inet */in_port_t Sin_port;    /* 16-bit TCP or UDP port number */* network byte ordered */struct IN_ADDR sin_addr; /* 32-bit IPV4 Address */* network byte ordered */char sin_zero[8];/* u nused */};/* Description: * Sin_len is to simplify the processing of the length variable socket address structure, the POSIX specification does not require this member; * Sin_bzero so that the socket address structure is at least 16 bytes in size; * S_addr, sin_family, Sin_port are POSIX data types.  The in_addr_t data type must be an unsigned integer of at least 32 bits, in_port_t must be an unsigned integer of at least 16 bits, * and sa_family_t is usually a 8-bit unsigned integer, but in implementations that do not support length fields, it is a 16-bit unsigned integer;    * The IPV4 address and TCP or UDP port number are stored in the socket address structure in network byte order; *//* IPV6 socket address structure *//* defined in the <netinet/in.h> header file */struct in6_addr{    uint8_t s6_addr[16];                    /* 128-bit IPV6 Address */* network byte ordered */}; #define Sin6_len       /* Required for Compile-time tests */struct sockaddr_in6{uint8_t Sin6_len;    /* Length of this struct (sa_family_t) */sin6_family;      /* AF_INET6 */in_port_t Sin6_port; /* Transport Layer port# */* Network byte ordered */uint32_t Sin6_flowinfo  ;      /* Flow information, undefined */struct IN6_ADDR sin6_addr;  /* IPV6 Address */* network byte ordered */uint32_t sin6_scope_id; /* Set of interfaces for a scope */};/*NOTE: * If the system supports the length field in the socket address structure, the Sin6_len constant must be defined; * The Sin6_flowinfo field is divided into two fields: low order 20 bits are stream, high-order 12 bits are reserved; * for addresses with range, the sin6_scope_id field identifies its *//* in order to use IPV6, a new universal socket address structure is defined *//* defined in the <netinet/in.h> header file */struct sockaddr_storage{uint8_t Ss_     Len  /* Length of this struct (implementation dependent) */sa_family_t ss_family; /* Address FAMILY:AF_XXX value */* implementation-dependent elements to provide: * 1) Alignment sufficient to Fu      Lfill the alignment requirments of all sockets address types that the system supports.     * 2) enough storage to hold any type of socket address, that the system suports. */};/* Description: * If the system supports any socket address structure alignment needs, then the new generic address structure to meet the most stringent alignment requirements; * The new address structure can accommodate any socket address structure supported by the system; */

BYTE Ordering

There are two ways in which a computer can store data in memory: A small-endian byte-order, a low-memory address that stores data in low bytes, high-memory addresses that store data in high bytes, and a big-endian byte order, which is a low-memory address that stores high-byte data, and a high-memory address that stores data low bytes;



The network byte order uses the big-endian byte order. The byte order used by a system is called the host byte order (also known as the processor byte order), the host byte order may be a small-endian byte order, or it may be a big-endian byte order. When processing multibyte data in a network protocol, the network byte order is used, that is, the big endian byte order, not the host byte order. To correspond the host byte order to the network byte order, the byte-order conversion function must be used, and the following is the conversion function between the host byte order and the network byte order:

/* Functions: Conversion between host byte order and network byte order; * Return value: Returns the byte order represented by the corresponding type; * Function prototype: */#include <arpa/inet.h>uint32_t htonl (uint32_t hostint32) ;//Return value: 32-bit integer represented by network byte order, uint16_t htons (uint16_t hostint16);//return value: 16-bit integer in network byte order; uint32_t Ntohl (uint32_t netint32) ;//Return value: 32-bit integer represented by host byte order; uint16_t Ntohs (uint16_t netint16);//return value: 16-bit integer represented by host byte order; * * Description: * From the above function we can find: * H means "host" byte order, n denotes "network" byte order, * L denotes "Long" integer, S denotes "short" integral type; * */

BYTE manipulation functions

/* Function: byte operation; * Function prototype: */#include <strings.h>void bzero (void *dest, size_t nbytes);//Initialize dest bytes stored data to 0 void bcopy (const void *str, void *dest, size_t nbytes);//Copy the data stored by STR to nbytes before dest bytes; int bcmp (const void *PTR1, const voi D *PTR2, size_t nbytes);//Compare the size of the previous nbytes byte of two characters, void *memset (void *dest, int c, size_t len)//Initialize the data stored by dest to the first Len byte of c;void *memcopy (void *dest,const void *src, size_t nbytes);//Copy the data stored in SRC before nbytes bytes to dest; int memcmp (const void *PTR1, const void *ptr2, size_t nbytes);//Compare the size of a two-character pre-nbytes byte;


Address Translation functions

To print the address of a network byte order into a format that we can understand, a conversion function is required to convert the network byte order into our readable address format, inet_ntop and Inet_pton, which convert the IP address format, which is defined as follows:

#include <arpa/inet.h>const char *inet_ntop (int domain, const void *restrict addr, char *restrict str, socklen_t size );//If successful returns the address string pointer, the error returns null;int Inet_pton (int domain, const char *restrict str, void *restrict addr);//If successful returns 1, invalid format returns 0 , the error returns -1;/* * Description: * Inet_ntop is to convert the network byte order binary address into a text string format; * Inet_pton is a binary address that converts a text string format into a network byte order; * parameter domain can only be value: Af_inet or af_in ET6; * *

Readn, writen, and ReadLine functions

The read and write functions on a byte-stream socket are different from normal file I/O. When we require multiple inputs or outputs, the read and write functions must be called multiple times, which is cumbersome. So we often use READN or writen functions.

#include "unp.h"/* Function function: read/write multiple byte stream; * Return value: The number of bytes read or written, or the -1;* function prototype if an error occurs: */ssize_t readn (int filedes, void *buff, size_t nbytes); s size_t writen (int filedes, const void *buff, size_t nbytes); ssize_t readline (int filedes, void *buff, size_t maxlen);

The specific implementation is as follows:

/* Include READN */#include "unp.h" ssize_t/* Read "n" bytes from a descriptor. */READN (int fd, void *vptr, size_t n) {size_tnleft;ssize_tnread;char*ptr;ptr = Vptr;nleft = N;while (Nleft > 0) {if (n Read = Read (FD, PTR, nleft)) < 0) {if (errno = = eintr) Nread = 0;/* and call read () again */elsereturn ( -1);} else if (NR EAD = = 0) break;/* EOF */nleft-= nread;ptr   + = nread;} return (n-nleft);/* return >= 0 */}/* End READN */

/* include writen */#include "unp.h" ssize_t/* Write "n" bytes to a descriptor. */writen (int fd, const void *vptr, size_t n) {size_tnleft;ssize_tnwritten;const char*ptr;ptr = Vptr;nleft = N;while (nleft > 0) {if (Nwritten = write (FD, PTR, nleft)) <= 0) {if (Nwritten < 0 && errno = = eintr) Nwritten = 0;/* A nd call write () again */elsereturn ( -1);/* ERROR */}nleft-= nwritten;ptr   + = Nwritten;} return (n);} /* End writen */

/* Include ReadLine */#include "unp.h" static intread_cnt;static char*read_ptr;static charread_buf[maxline];static  Ssize_tmy_read (int fd, char *ptr) {if (read_cnt <= 0) {again:if ((read_cnt = Read (fd, read_buf, sizeof (READ_BUF))) < 0) {if (errno = = eintr) goto Again;return ( -1);} else if (read_cnt = = 0) return (0); read_ptr = Read_buf;} Read_cnt--;*ptr = *read_ptr++;return (1);}  Ssize_treadline (int fd, void *vptr, size_t maxlen) {ssize_tn, rc;charc, *ptr;ptr = vptr;for (n = 1; n < maxlen; n++) {if (rc = My_read (FD, &c) = = = 1)  {*ptr++ = c;if (c = = ' \ n ') break;/* newline is stored, like fgets () */} else if (rc = = 0) {*ptr = 0;return (n-1);/* EOF, N -1 bytes were read */} elsereturn ( -1);/* error, errno set by Read () */}*ptr = 0;/* null terminate like Fgets () */return ( n);} Ssize_treadlinebuf (void **vptrptr) {if (read_cnt) *vptrptr = Read_ptr;return (read_cnt);} /* End ReadLine */ssize_treadline (int fd, void *ptr, size_t maxlen) {ssize_tn;if ((n = readline (fd, PTR, maxlen)) < 0) E Rr_sys ("ReadLine error "); return (n);} 

Resources:

"Unix Network Programming"

Introduction to programming of network programming sockets

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.