Socket learning day2
tcp three-way handshake and four-way handshake
- the three-way handshake
1.SYN:2000(0) mss<1024>(c->s)
SYN:the serial number; mss: maximum segment(报文) size
2.SYN:5000(0) ACK:2001 mss<1024>(s->c)
ACK:the SYN add 1
3.ACK:5001 (c->s)
ACK:the SYN add 1
- the data transmission
1.Seq:2001(20)(c->s)
client send serial 2001,2020 to server
2.Seq:5001(50) ACK:2021(s->c)
server send serial 5001,5050 to client
ack equals 2020 add 1
3.ACK:5051(c->s)
ack equals 5050 add 1
- the cutdown of connection
1.FIN:5051 ACK:2021(s->c)
FIN:5051 equals ACK upon
ACK:2021 equals last ack
2.ACK:5052(c->s)
ack equals fin add 1
3.FIN:2021 ACK:5052(c->s)
fin equals ack
ack equals last ack
4.ACK:2022(s->c)
ack equals fin add 1
the code of socket_server by multiply process
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<ctype.h>
#include "wrap.h"
int main(){
//1.build socket
int lfd = Socket(AF_INET, SOCK_STREAM, 0);
//2.bind the socket
struct sockaddr_in serv;
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
Bind(lfd, (struct sockaddr *)&serv, sizeof(serv));
//3.listen the client
Listen(lfd, 128);
int cfd;
pid_t pid;
struct sockaddr_in client;
int len;
char sIP[16];//record the ip of client
while(1){
len = sizeof(client);
memset(sIP, 0x00, sizeof(sIP));
//accept the client request
cfd = Accept(lfd, (struct sockaddr *)&client, &len);
printf("client port==%d ip==%s\n", ntohs(client.sin_port), inet_ntop(AF_INET, &client.sin_addr.s_addr, sIP, sizeof(sIP)));
//make a son process to handle the data
pid = fork();
if(pid < 0){
perror("fork error");
exit(-1);
}else if(pid > 0){
//close the cfd
close(cfd);
}else if(pid == 0){
//close the lfd
close(lfd);
int i;
int n;
char buf[1024];
//memset(buf, 0x00, sizeof(buf));
while(1){
n = Read(cfd, buf, sizeof(buf));
if(n <= 0){
printf("read error or client closed,n==%d",n);
break;
}
printf("client port==%d, n==%d, buf==%s\n", ntohs(client.sin_port), n, buf);
for(i = 0; i < n; i++){
buf[i] = toupper(buf[i]);
}
Write(cfd, buf, n);
}
close(cfd);
exit(0);
}
}
close(lfd);
return 0;
}
}
close(cfd);
exit(0);
}
}
close(lfd);
return 0;
}