tcp_process(struct tcp_pcb pcb)函数进行此插口(socket)状态的转移和处理 if ((pcb->flags & TF_RXCLOSED) == 0) { / Update the PCB (in)activity timer unless rx is closed (see tcp_shutdown) */ pcb->tmr = tcp_ticks; } 如果没有关闭的话 更新此链接的保活时间
/* Do different things depending on the TCP state. */ switch (pcb->state) { CLOSED = 0, LISTEN = 1, SYN_SENT = 2, SYN_RCVD = 3, ESTABLISHED = 4, FIN_WAIT_1 = 5, FIN_WAIT_2 = 6, CLOSE_WAIT = 7, CLOSING = 8, LAST_ACK = 9, TIME_WAIT = 10 如上图进行状态转换 case SYN_SENT:
/* received SYN ACK with expected sequence number? */
if ((flags & TCP_ACK) && (flags & TCP_SYN)
&& (ackno == pcb->lastack + 1)) {
pcb->state = ESTABLISHED;
主动打开 这边收到之后就已经建立连接,然后设置ack位 tcp_input函数判断此位然后发送ack包
tcp_ack_now(pcb);
}
/* received ACK? possibly a half-open connection */
else if (flags & TCP_ACK) {
这只有可能对面也在主动打开 , 但是我们没有收到syc ,否则我们就进入 SYN_RCVD 状态了(如图)
/* send a RST to bring the other side in a non-synchronized state. */
tcp_rst(pcb, ackno, seqno + tcplen, ip_current_dest_addr(),
ip_current_src_addr(), tcphdr->dest, tcphdr->src);
}
case SYN_RCVD: if (flags & TCP_ACK) { /* expected ACK number? / if (TCP_SEQ_BETWEEN(ackno, pcb->lastack + 1, pcb->snd_nxt)) { pcb->state = ESTABLISHED; 这是被动打开 ,收到ack说明握手成功,如果此时也收到关闭进入关闭逻辑 if (recv_flags & TF_GOT_FIN) { tcp_ack_now(pcb); pcb->state = CLOSE_WAIT; } } else { 如果ack号不匹配握手失败 rst; / incorrect ACK number, send RST / tcp_rst(pcb, ackno, seqno + tcplen, ip_current_dest_addr(), ip_current_src_addr(), tcphdr->dest, tcphdr->src); } } else if ((flags & TCP_SYN) && (seqno == pcb->rcv_nxt - 1)) { 如果发来了重复的syn,就重新发送syn-ack / Looks like another copy of the SYN - retransmit our SYN-ACK */ tcp_rexmit(pcb); } break;
case CLOSE_WAIT: /* FALLTHROUGH / case ESTABLISHED: tcp_receive(pcb);//时候据的话就会调用用户回调函数 //被动 关闭 收到fin 发 ack if (recv_flags & TF_GOT_FIN) { / passive close */ tcp_ack_now(pcb); pcb->state = CLOSE_WAIT; } break; case FIN_WAIT_1: tcp_receive(pcb); if (recv_flags & TF_GOT_FIN) {//同时关闭 if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt) &&
tcp_ack_now(pcb);
tcp_pcb_purge(pcb);
TCP_RMV_ACTIVE(pcb);
pcb->state = TIME_WAIT;
TCP_REG(&tcp_tw_pcbs, pcb);
} else {
tcp_ack_now(pcb);
pcb->state = CLOSING;
}
} else if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt) &&
pcb->unsent == NULL) {
pcb->state = FIN_WAIT_2;
}
break;
|