main
|-----.....
|-----tracker_mem_init
|-----socketServer
|-----tcpsetserveropt
|-----.....
socketServer函数在main函数中被调用的代码:
-
sock = socketServer(bind_addr, g_server_port, &result);//创建socket,绑定,监听
-
if (sock < 0)
-
{
-
log_destroy();
-
return result;
-
socketServer函数代码:
-
int socketServer(const char *bind_ipaddr, const int port, int *err_no)
-
{
-
int sock;
-
int result;
-
//创建socket,AF_INET:ipv4因特网,SOCK_STREAM:有序,可靠,双向的面向链接的字节流
-
//0表示按照给定的域和套接字类型选择默认的协议
-
sock = socket(AF_INET, SOCK_STREAM, 0);//创建socket,AF_INET:ipv4因特网
-
if (sock < 0)
-
{
-
*err_no = errno != 0 ? errno : EMFILE;
-
logError("file: "__FILE__", line: %d, " \
-
"socket create failed, errno: %d, error info: %s", \
-
__LINE__, errno, STRERROR(errno));
-
return -1;
-
}
-
-
result = 1;
-
//SO_REUSEADDR:表示如果result为非0,则重用bind中的地址
-
//SOL_SOCKET:表示通用的套接字层
-
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &result, sizeof(int))<0)
-
{
-
*err_no = errno != 0 ? errno : ENOMEM;
-
logError("file: "__FILE__", line: %d, " \
-
"setsockopt failed, errno: %d, error info: %s", \
-
__LINE__, errno, STRERROR(errno));
-
close(sock);
-
return -2;
-
}
-
//绑定sock到指定的ip地址与端口上
-
if ((*err_no=socketBind(sock, bind_ipaddr, port)) != 0)
-
{
-
close(sock);
-
return -3;
-
}
-
-
if (listen(sock, 1024) < 0)//服务器监听,1024表示请求队列的大小
-
{
-
*err_no = errno != 0 ? errno : EINVAL;
-
logError("file: "__FILE__", line: %d, " \
-
"listen port %d failed, " \
-
"errno: %d, error info: %s", \
-
__LINE__, port, errno, STRERROR(errno));
-
close(sock);
-
return -4;
-
}
-
-
*err_no = 0;
-
return sock;
-
}
socketSever函数执行步骤:
(1) 调用socket函数,创建socket,并获得socket id
(2) 调用setsockopt函数,设定socket选项
(3) 调用socketBind绑定socket到特定ip地址
(4) 调用listen函数,监听socket
上述步骤中,socket,setsockopt,listen函数均为系统调用
socketBind函数代码:
-
int socketBind(int sock, const char *bind_ipaddr, const int port)
-
{
-
struct sockaddr_in bindaddr; //sockaddr_in表示英特网sock结构
-
-
bindaddr.sin_family = AF_INET;
-
bindaddr.sin_port = htons(port);//主机字节序转换成网络字节序,l表示32位,s表示16位
-
if (bind_ipaddr == NULL || *bind_ipaddr == '\0')
-
{
-
bindaddr.sin_addr.s_addr = INADDR_ANY;
-
}
-
else
-
{
-
//把ip字符串转换成ip地址
-
if (inet_aton(bind_ipaddr, &bindaddr.sin_addr) == 0)
-
{
-
logError("file: "__FILE__", line: %d, " \
-
"invalid ip addr %s", \
-
__LINE__, bind_ipaddr);
-
return EINVAL;
-
}
-
}
-
//绑定socket
-
if (bind(sock, (struct sockaddr*)&bindaddr, sizeof(bindaddr)) < 0)
-
{
-
logError("file: "__FILE__", line: %d, " \
-
"bind port %d failed, " \
-
"errno: %d, error info: %s.", \
-
__LINE__, port, errno, STRERROR(errno));
-
return errno != 0 ? errno : ENOMEM;
-
}
-
-
return 0;
-
}
socketBind执行步骤:
(1) 调用honts函数,先把端口转换成网络字节序
(2) 调用inet_aton函数,把ip地址字符串转换成ip地址结构
(3) 调用bind函数,绑定socket到特定ip地址
阅读(827) | 评论(0) | 转发(0) |