Beej’s Guide Network to Programming 系列连载09
5.2. socket() ---获得文件描述符
我不想长篇大论---我要谈的调用系统函数socket()。下面是他的原型:
#include<sys/types.h>
#include<sys/socket.h>
int socket(intdomain, int type, int protocol);
但是这些参数干什么的呢?他们允许你使用哪种套接字(IPv4还是IPv6;TCP还是UDP)。
它曾经是人们将这些值进行硬编码,你也可以这么做。(domain可以选择PF_INET或者PF_INET6;type可以选择SOCK_STREAM或者SOCK_DGRAM;protocol设置为0,或者你可以调用getprotobyname()来查找你想要的协议,“tcp”或“UDP” 。)
译者注:SOCK_STREAM等同于TCP;SOCK_DGRAM等同于UDP。所以你不用费二遍事再作一次J
(编者在这儿又叙述了一下PF_*与AF_*的一些关系)
译者注:他们其实是等同的,有兴趣的读者可以看《UnixNetwork Programming》第一卷中第四章第2节中的“AF_xxxVersus PF_xxx”
你真正要做的是把调用getaddrinfo()得到的结果值,直接给socket()函数使用像下面这样:
int s;
struct addrinfohints, *res;
// do the lookup
// [pretend wealready filled out the “hints” struct]
getaddrinfo(www.example.com, “http”, &hints,&res);
// [again, youshould do error-checking on getaddrinfo(), and walk
// the “res”linked list looking for valid entries instead of just
// assuming thefirst one is good (like many of these example do.)
// See the sectionon client/server for real examples.]
s =socket(res->ai_family, res->ai_socktype, res->ai_protocol);
socket()函数只是简单地返回给你一个套接字描述符,以供其后的其它系统函数使用;或者返回-1错误。全局变量errno是设置错误值的。(errno详见man文档)
好,好,好!但是使用这样的方式有什么益处吗?答案就是:简洁!
摘自 xiaobin_HLJ80的专栏