Linux under Socket Programming Foundation--socket address API__HTML5

Source: Internet
Author: User

Socket programming refers to a complete set of API programming about sockets, not just the use of socket () system calls, but also a complete set of functions around this system call. Here we will start from the basics and learn how to write the socket program initially. host byte order and network byte order

To learn about socket programming, first understand what a byte order is.

The accumulator of modern CPUs can load (at least) 4 bytes at a time (consider 32 machines here, below). So the order of the 4 bytes in memory will affect the value that the accumulator loads into integers, which is the byte-order problem. Byte order is divided into big endian and small endian (little endian). The big-endian byte sequence refers to an integer's high byte at the low address of the memory, and the small-end byte-order refers to the low byte of an integer at the lower address of the memory. Here is a program to test the machine byte sequence:

#include <stdio.h>

int main ()
{
    union{short
        s;
        Char c[sizeof (short)];
    Test;

    Test.s = 0x1234;

    if ((test.c[0] = = 0x34) && (test.c[1] = = 0x12)) {
        printf ("Little endian\n");
    } Else ((test.c[0] = = 0x12) && (test.c[1] = = 0x34)) {
        printf ("Big endian\n");
    } else{
        printf ("unknow...\n");
    }

Modern PCs are mostly small-endian, so the small-end byte order is also called host byte-order.

When formatted data (such as 32bit integers and 16bit short integers) are transmitted on two hosts that use a different byte sequence, the receiving end must be incorrectly interpreted. The solution is to make a unified format, are used to send and receive a big-endian byte order, so the big-endian byte sequence is called the network byte order.

It should be noted that even though two processes on the same host (one written in C and one in Java), it is also necessary to consider the byte-order problem (the Java Virtual machine uses a big-endian byte sequence).

Linux provides the following four functions to complete host byte-order and network byte-order conversions:

#include <netinet/in.h>
unsigned long int htonl (unsigned long int hostlong);
unsigned short int htons (unsigned short int hostshort);
unsigned long int ntohl (unsigned long int netlong);
unsigned short int ntohs (unsigned short int netshrot);

How to remember them, take an example: Htonl says "host to network Long".
In these four functions, Long integer functions are typically used to convert IP addresses, and short integer functions are used to convert port numbers . Universal Socket Address

The socket network programming interface represents the structure body sockaddr of the socket address, which is defined as follows:

#include <bits/socket.h>
struct sockaddr
{
    sa_family_t sa_family;
    Char sa_data[14];

The sa_family member is a variable of the address family type (sa_family_t). The address family type usually corresponds to the protocol type. The Common protocol family (protocol family, also known as domain) and the corresponding address family are the following table:

Protocol Family Address Family Description
Pf_unix Af_unix UNIX Native Domain Agreement family
Pf_inet Af_inet Tcp/ipv4 Protocol Family
Pf_inet6 Af_inet6 Tcp/ipv6 Protocol Family

Macros pf_* and af_* are both defined in bits/socket.h and have exactly the same value, so they can be mixed.

The Sa_data member holds the socket address value, but the address value of the different protocol family has different meanings and lengths. As shown in the following table:

Protocol Family address value meaning and length
Pf_unix The path name of the file, up to 108 bytes in length
Pf_inet 16bit port number and 32bit IPV4 address, total 6 bytes
Pf_inet6 16bit port number and 32bit stream identification, 128bit IPV6 address, 32bit range ID, total 26 bytes

As can be seen from the above table, 14-byte sa_data cannot fully accommodate the address values of most protocol families. As a result, Linux defines the following new generic socket address structure:

#include <bits/socket.h>
struct sockaddr_storage
{
    sa_family_t sa_family;
    unsigned long int __ss_align;
    Char __ss_padding[128-sizeof (__ss_align)];

This structure not only provides a large enough space for address values, but also memory-aligned (this is the role of __ss_align members) dedicated socket address

The above two common socket address structures are obviously not very useful, such as setting and getting the IP address and port number long need to perform cumbersome bit operations. So Linux provides a special socket address structure for each protocol family.

The UNIX local domain protocol family uses the following private socket address structure:

#include <sys/un.h>
struct sockaddr_un
{
    sa_family_t sa_family;/* address Family protocol: Af_unix/
    Char Sun_ PATH[108]; /* File path name *
/};

The TCP/IP protocol family has sockaddr_in and SOCKADDR_IN6 two dedicated socket address structures, which are used for IPV4 and IPV6 respectively:

struct sockaddr_in
{
    sa_family sin_family;/* address family: af_inet
    /u_int16_t sin_port;/* port number (network byte order) * *
    struct IN_ADDR sin_addr;/* IPV4 address structure, see *
/};
struct in_addr
{
    u_int32_t s_addr;/* IPv4 address (network byte order) */
};

struct SOCKADDR_IN6
{
    sa_family_t sin6_family;/* address family: af_int6
    /u_int16_t sin6_port;/* port number (network byte order) * *
    u_int32_t sin6_flowinfo;/* Flow information should be set to 0/
    struct IN6_ADDR sin6_addr;/* IPV6 address structure, see below * *
    u_int32_t sin6_ scope_id;/* Scope ID, still in experimental phase
/}
struct in6_addr
{
    unsigned char sa_addr[16];/* IPv6 address (network byte order) */< c20/>}

The meanings of the fields in these two dedicated socket address structures are clear, and all the special socket address (and sockaddr_storage) types of variables need to be converted to universal socket address type SOCKADDR (CAST) when they are actually used. Because the type of address parameter used by all socket programming interfaces is sockaddr. IP Address conversion function

In general, we are accustomed to using strings to represent IP addresses, such as "192.168.1.1", which need to convert this string IP to struct in_addr type when doing socket programming, and the following functions provide address type conversions.

#include <arpa/inet.h>
in_addr_t inet_addr (const char *strptr);
int Inet_aton (const char *cp,struct in_addr *INP);
char* Inet_ntoa (struct in_addr in);

The INET_ADDR function converts the IPV4 address represented by a dotted decimal string to the IPV4 address represented by a network byte-ordered integer. Returns Inaddr_none when it fails.

The Inet_aton function completes inet_addr the same function, but the transformation result exists in the INP point IN_ADDR address structure body.

The Inet_ntoa function converts the IPV4 address represented by a network byte-ordered integer to a IPv4 address represented by a dotted decimal string. However, it is important to note that the function internally uses a static variable to store the transformation result, and the return value of the function points to the static memory, so that the Inet_ntoa is not reentrant. The following code shows this type of non reentrant:

Char *szvaule1 = Inet_ntoa (/*1.2.3.4*/);
Char *szvalue2 = Inet_ntoa (/*5.6.7.8*/);
printf ("%s\n", szVaule1);
printf ("%s\n", szVaule2);

The result:
5.6.7.8
5.6.7.8

There are also IPV6 (also compatible IPv4):

#include <arpa/inet.h>
int inet_pton (int af,const char *src,void *dst);
Const char* inet_ntop (int af,const void *src,char *dst,socklen_t cnt);

Here I do not know for a moment, now IPv4 for me is enough, and then need to further study it.

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.