int socket(int domain,int type,int protocol) int domain: AF_UNIX(本机通信),AF_INET(TCP/IP-IPv4),AF_INET6(TCP/IP-IPv6) int type: SOCK_STREAM(TCP),SOCK_DGRAM(UDP),SOCK_RAW int protocol =0确定套接字需要的协议簇和类型 返回值:成功返回套接字,失败返回-1,错误代码写入“errno”
1.2将socket连接到服务器
通过socket连接到远程服务器,需要ip地址和端口号进行连接
1.2.1 创建sockaddr_in结构
1
struct sockaddr_in server;
sockaddr_in 结构如下面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// IPv4 AF_INET sockets: struct sockaddr_in { short sin_family; // e.g. AF_INET, AF_INET6 unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to };
struct in_addr { unsigned long s_addr; // load with inet_pton() };
if ( (he = gethostbyname( hostname ) ) == NULL) { //gethostbyname failed herror("gethostbyname"); return 1; } //Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only addr_list = (struct in_addr **) he->h_addr_list;
for(i = 0; addr_list[i] != NULL; i++) { //Return the first one; strcpy(ip , inet_ntoa(*addr_list[i]) ); }
作者: Neil Gaiman 尼尔 盖曼 Fairy tales are more than true: not because they tell us that dragons exist, but because they tell us that dragons can be beaten.