原文:https://beej.us/guide/bgnet/html/#socket
5.2 socket --- 获得文件描述符
我不想长篇大论---我要谈的调用系统函数socket()。下面是他的原型:
#include<sys/types.h>
#include<sys/socket.h>
int socket(int domain, int type, int protocol);
- domain 可以选择PF_INET或者PF_INET6;
- type 可以选择SOCK_STREAM或者SOCK_DGRAM;
- protocol 设置为0,或者你可以调用getprotobyname()来查找你想要的协议,“tcp”或“UDP”
它曾经是人们将这些值进行硬编码,你也可以这么做。
译者注:SOCK_STREAM等同于TCP;SOCK_DGRAM等同于UDP。
(编者在这儿又叙述了一下PF_*与AF_*的一些关系)
译者注:他们其实是等同的,
有兴趣的读者可以看《Unix Network Programming》第一卷中第四章第2节中的“AF_xxx Versus PF_xxx”
你真正要做的是把调用getaddrinfo()得到的结果值,直接给socket()函数使用像下面这样:
int s;
struct addrinfo hints, *res;
// do the lookup
// [pretend we already filled out the "hints" struct]
getaddrinfo("www.example.com", "http", &hints, &res);
// again, you should do error-checking on getaddrinfo(), and walk
// the "res" linked list looking for valid entries instead of just
// assuming the first one is good (like many of these examples do).
// See the section on client/server for real examples.
s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
socket()函数只是简单地返回给你一个套接字描述符,以供其后的其它系统函数使用;或者返回-1错误。全局变量errno是设置错误值的。(errno详见man文档)
好,好,好!但是使用这样的方式有什么益处吗?
答案就是:简洁!