//创建socket
int socket(int domain, int type, int protocol);
参数:domain
AF_INET(IPv4) AF_INET6(IPv6) AF_UNIX, AF_LOCAL(UNIX_IP)
参数:type
SOCK_STREAM(流式) SOCK_DGRAM(数据报式)
参数: protocal(通常给0)
Normally only a single protocol exists to support a particular socket type within a given protocol family, in which case protocol can be specified as 0.
成功返回一个文件句柄,否则返回-1.
typedef unsigned short int sa_family_t;
struct sockaddr {
sa_family_t sa_family; //地址类型 (AF_INET...)
char sa_data[14]; //14个字节的端口号和地址
}
IPv4
struct sockaddr_in {
sa_family_t sin_family; /* address family: AF_INET */
in_port_t sin_port; /* port in network byte order */
struct in_addr sin_addr; /* internet address */
};
struct in_addr {
uint32_t s_addr; /* address in network byte order */
};
IPv6
struct sockaddr_in6 {
sa_family_t sin6_family; /* AF_INET6 */
in_port_t sin6_port; /* port number */
uint32_t sin6_flowinfo; /* IPv6 flow information */
struct in6_addr sin6_addr; /* IPv6 address */
uint32_t sin6_scope_id; /* Scope ID (new in 2.4) */
};
struct in6_addr {
unsigned char s6_addr[16]; /* IPv6 address */
};
大段小端转换
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.
The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.
The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
struct hostent *gethostbyname(const char *name);
此函数可以利用字符串格式的域名获得网络字节顺序的地址。
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
#define h_addr h_addr_list[0] /* for backward compatibility */