Socket 結構

有各種不同的Unix套接字編程結構,用來保存地址和端口信息和其他信息。大多數socket函數需要一個指向一個socket地址結構作爲參數。在本教程中定義的結構與互聯網協議的家族。

第一個結構是struct sockaddr的持有套接字信息:

struct sockaddr{
unsigned short sa_family;
char sa_data[14];
};

這是一個通用的套接字地址結構在大部分的套接字函數調用,將被傳遞。這裏是成員字段的描述:

屬性

描述

sa_family

AF_INET
AF_UNIX
AF_NS
AF_IMPLINK

This represents an address family. In most of the Internet based applications we use AF_INET.

sa_data

Protocol Specific Address

The content of the 14 bytes of protocol specific address are interpreted according to the type of address. For the Internet family we will use port number IP address which is represented bysockaddr_in structure defined below.

第二個結構,幫助引用套接字的元素如下:

struct sockaddr_in {
short int sin_family;
unsigned short int sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[8];
};

這裏是成員字段的描述:

屬性

描述

sa_family

AF_INET
AF_UNIX
AF_NS
AF_IMPLINK

This represents an address family. In most of the Internet based applications we use AF_INET.

sin_port

Service Port

A 16 bit port number in Network Byte Order.

sin_addr

IP Address

A 32 bit IP address in Network Byte Order.

sin_zero

Not Used

You just set this value to NULL as this is not being used.

下一個結構僅用於上述結構中的一個結構域,並擁有32位的netid/主機ID。

struct in_addr {
unsigned long s_addr;
};

這裏是成員字段的描述:

屬性

描述

s_addr

service port

A 32 bit IP address in Network Byte Order.

還有一個更重要的結構。這個結構是用來保持主機相關的信息。

struct hostent
{
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list
#define h_addr h_addr_list[0]
};

這裏是成員字段的描述:

屬性

描述

h_name

ti.com etc

This is official name of the host. For example tutorialspoint.com, google.com etc.

h_aliases

TI

This will hold a list of host name aliases.

h_addrtype

AF_INET

This contains the address family and in case of Internet based application it will always be AF_INET

h_length

4

This will hold the length of IP address which is 4 for Internet Address.

h_addr_list

in_addr

For the Internet addresses the array of pointers h_addr_list[0], h_addr_list[1] and so on are points to structure in_addr.

注: h_addr被定義爲h_addr_list[0],以保持向後兼容。.

下面的結構是用來保持服務和相關聯的端口有關的信息。

struct servent
{
char *s_name;
char **s_aliases;
int s_port;
char *s_proto;
};

這裏是成員字段的描述:

屬性

描述

s_name

http

這是官方的服務名稱。例如SMTP,FTP POP3等。

s_aliases

ALIAS

其將存放服務別名的列表。大部分的時間將被設置爲NULL。

s_port

80

這將有相關聯的端口號。例如HTTP,則爲80。

s_proto

TCP 
UDP

這將被設置爲所使用的協議。使用TCP或UDP網絡服務。

套接字結構上的提示:

套接字地址結構是每一個網絡程序的一個組成部分。我們分配填補在指針傳遞給它們的各種套接字函數。有時候,我們通過一個這樣的結構指針的socket函數,它填補了的內容。

我們總是通過引用傳遞這些結構(即我們傳遞一個指針的結構,而不是結構本身),我們總是通過結構的大小作爲另一個參數。

當套接字函數填充在一個結構中,長度也通過引用傳遞的,因此它的值由該函數可以被更新。我們稱這些結果值參數。

請務必將結構體變量設置爲NULL(即'\0')用memset()的bzero()函數,否則在你的結構,它可能會得到意想不到的垃圾值。