The address structure of the socket

Source: Internet
Author: User
Tags bind socket port number

In the process of establishing the socket communication, the address plays a key role in the design of TCP/IP network program, must have a clear understanding of the address structure of the socket.

The address data structure of TCP/IP.

struct SOCKADDR {
U_short safamily;/* address Family, af_xxx*/
Specific protocol address for Char sa_data[14];/*14 byte
}

The 14-byte sa_data varies with the protocol. In the TCP/IP protocol family, the address data structure is:

struct in_addr{
U_long s_addr;/*32 bit IP address, network byte order * *
};
struct sockaddr_in{
Short sin_family; /*af_inet*/
U_short Sin_short; /*16 bit port number, network byte order *
struct IN_ADDR sin_addr; /*32 bit IP address, network byte order * *
Char Sin_zero[8]; /* Not used * *
}

Network byte order is a set of data representation format in TCP/IP, which is independent of specific CPU type, operating system, etc., so that data can be interpreted correctly when transmitting between different hosts. The two functions converted from host byte order to network byte order are as follows: Htons (): Converts 16-bit host byte order data to network byte order htonl (): Converts 32-bit host byte-order data to network byte order the corresponding function to convert the network byte order to host byte order is:

Ntohs (): Converts 16-bit network byte-order data to host byte Order Ntohl (): Converts 32-bit network byte order data to host byte order because of the length of the various socket address structures, the TCP/IP address family address length is 8 bytes, The Xns address is 14 bytes, the UNIX address is indeterminate, up to 110 bytes long, so it cannot be defined in a uniform format, and the length of the socket address needs to be explicitly specified in the bind () call.

When the bind () parameter is invalid or the port is already in the other program, the function returns-1, indicating that the socket name failed.

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.