从学通信的博士到从事IT行业的工程师 从原华为项目经理,到现任职公司架构师
分类: LINUX
2013-01-25 00:27:38
Linux内核在3.6和3.7合入了TCP Fast Open特性,在3.7.3版本上验证了一下,I did it!
以下是C语言实例():
server端代码:
#include
#include
#include
#include
int main(){
int portno = 5060;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int cfd;
int sfd = socket(AF_INET, SOCK_STREAM, 0); // Create socket
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
bind(sfd, &serv_addr,sizeof(serv_addr)); // Bind to well known address
int qlen = 5; // Value to be chosen by application
int err = setsockopt(sfd, IPPROTO_TCP/*SOL_TCP*/, 23/*TCP_FASTOPEN*/, &qlen, sizeof(qlen));
listen(sfd,1); // Mark socket to receive connections
cfd = accept(sfd, NULL, 0); // Accept connection on new socket
while(1){
int len = read(cfd,buffer,256);
if(len)
printf("tcp fast open: %s\\n",buffer);
else
break;
// read and write data on connected socket cfd
}
close(cfd);
}
client端代码:
#include
#include
#include
#include
int main(){
struct sockaddr_in serv_addr;
struct hostent *server;
char *data = "Hello, tcp fast open";
int data_len = strlen(data);
int sfd = socket(AF_INET, SOCK_STREAM, 0);
server = gethostbyname("localhost");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(5060);
int len = sendto(sfd, data, data_len, 0x20000000/*MSG_FASTOPEN*/,
(struct sockaddr *) &serv_addr, sizeof(serv_addr));
printf("error: %s\\n",strerror(errno));
close(sfd);
sleep(5);
}
执行结果:
# ./server
tcp fast open: Hello, tcp fast open
# ./client
error: Success
环境:Fedora 18 升级内核到3.7.3;glibc 2.17;gcc 4.7.2
记得要执行: echo 1 > /proc/sys/net/ipv4/tcp_fastopen