What is the difference between struct sockaddr_in and struct sockaddr?

Source: Internet
Author: User

struct sockaddr {
unsigned short sa_family;/* address family, af_xxx */
char sa_data [14]; /* 14-byte Protocol address */
};
the above is a general socket address, specific to the internet socket, with the following structure, the two types can be converted.
struct sockaddr_in {
short int sin_family;/* address family */
unsigned short int sin_port; /* Port Number */
struct in_addr sin_addr;/* Internet address */
unsigned char sin_zero [8]; /* the same length as struct sockaddr */
};
Struct in_addr is a 32-bit IP address.
struct in_addr {
unsigned long s_addr;
};

Yes
Struct in_addr {
Union {
Struct {u_char s_b1, s_b2, s_b3, s_b4;} s_un_ B;
Struct {u_short s_w1, s_w2;} s_un_w;
U_long s_addr;
} S_un;
};
Use u_long htonl (u_long hostlong); to convert the host's byte sequence to the TCP/IP network's byte sequence.
Use u_short htons (u_short hostshort) to convert host byte to TCP/IP network byte.

Inet_addr () is to convert a point-based IP address (such as 192.168.0.1) to the 32-bit IP address (0xc0a80001) required in the preceding structure ).

The common usage is:
Int sockfd;
Struct sockaddr_in my_addr;
Sockfd = socket (af_inet, sock_stream, 0);/* do some error checks! */

My_addr.sin_family = af_inet;/* Host byte order */
My_addr.sin_port = htons (myport);/* short, network byte order */
My_addr.sin_addr.s_addr = inet_addr ("192.168.0.1 ");

Bzero (& (my_addr.sin_zero), 8);/* zero the rest of the struct */
/* Do not forget to perform an error check for BIND :*/
BIND (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr ));

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.