/*
引數釋義:
addr:傳入服務器地址資訊,其中內容將用于創建監聽套接字
source_addr:相當于客戶端地址資訊
flags:這我還真沒看明白,,,再最后一塊兒,注釋給出了,如果沒猜錯,應該是和僅打開監聽套接字有關的
*/
static int anetTcpGenericConnect(char *err, const char *addr, int port,const char *source_addr, int flags)
{
int s = ANET_ERR, rv;
char portstr[6]; /* strlen("65535") + 1; */
struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
snprintf(portstr,sizeof(portstr),"%d",port);
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC; //未指定
hints.ai_socktype = SOCK_STREAM;//有序、可靠、面向連接的雙向位元組流
if ((rv = getaddrinfo(addr,portstr,&hints,&servinfo)) != 0) { //決議addr資訊,存入 servinfo
//不懂一定要看上面的工具包,寫了一晚上呢
anetSetError(err, "%s", gai_strerror(rv)); //這個不管它,報錯函式而已
return ANET_ERR;
}
for (p = servinfo; p != NULL; p = p->ai_next) { //工具包里有說,給你一個addrinfo,它可能是一串
/* Try to create the socket and to connect it.
* If we fail in the socket() call, or on connect(), we retry with
* the next entry in servinfo. */
if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) //這里s成為了監聽套接字
continue; //如果沒打開,那就繼續回圈,無礙
if (anetSetReuseAddr(err,s) == ANET_ERR) goto error; //設定地址重用
if (flags & ANET_CONNECT_NONBLOCK && anetNonBlock(err,s) != ANET_OK) //設定非阻塞
goto error;
if (source_addr) { //source_addr:傳入引數
int bound = 0;
/* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0) //內啥,不多說了啊
{
anetSetError(err, "%s", gai_strerror(rv));
goto error;
}
for (b = bservinfo; b != NULL; b = b->ai_next) {
if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
bound = 1;
break;
}
}
freeaddrinfo(bservinfo);
if (!bound) {
anetSetError(err, "bind: %s", strerror(errno));
goto error;
}
} //for回圈到這里結束
if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
/* If the socket is non-blocking, it is ok for connect() to
* return an EINPROGRESS error here. */
if (errno == EINPROGRESS && flags & ANET_CONNECT_NONBLOCK)
goto end;
close(s);
s = ANET_ERR;
continue;
}
/* If we ended an iteration of the for loop without errors, we
* have a connected socket. Let's return to the caller. */
goto end;
}
if (p == NULL)
anetSetError(err, "creating socket: %s", strerror(errno));
error:
if (s != ANET_ERR) {
close(s);
s = ANET_ERR;
}
end:
freeaddrinfo(servinfo);
/* Handle best effort binding: if a binding address was used, but it is
* not possible to create a socket, try again without a binding address. */
if (s == ANET_ERR && source_addr && (flags & ANET_CONNECT_BE_BINDING)) {
//#define ANET_CONNECT_BE_BINDING 2 /* Best effort binding. */
return anetTcpGenericConnect(err,addr,port,NULL,flags);
} else {
return s;
}
}
如果還有什么疑惑,可以在評論區留言一起討論哦,
相見即是緣分,最近正在寫《redis原始碼學習》系列,可以在我的主頁找到,
何妨來個關注呢?

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22055.html
標籤:java
