标签:
之前一直以为time_wait状态就是主动关闭的那一方产生.然后这个端口一直不可以用.实际我发现服务端监听一个端口.客户端发来连接后.传输数据后.服务端关闭客户端套接字后.用netstat -nat | grep 端口 查看了产生了time_wait.但客户端依然可以不断连接服务端.然后服务端不断关闭.并不会影响监听端口.原来是只有服务端把监听端口描述符给关闭(不是accept那个连接.虽然,端口相同),在2mls时间内再次启动这个端口..就会提示Address already in use
#include "unp.h"
int main(int argc,char *argv[])
{ if(argc<2)
{
printf("please input server_ip\n");
return 0;
}
int fd=socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
err_quit("socket create error");
struct sockaddr_in servaddr;
struct sockaddr_in clientaddr;
clientaddr.sin_family=AF_INET;
clientaddr.sin_port=htonl(5900);
clientaddr.sin_addr.s_addr=htons(INADDR_ANY);
bind(fd,(SA*)&clientaddr,sizeof(clientaddr));`
servaddr.sin_family=AF_INET;//message proctoal
servaddr.sin_port=htons(13);
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<0)
err_quit("inet_pton error");
if(connect(fd,(SA*)&servaddr,sizeof(servaddr))<0)
err_quit("connect error");
char buf[1024];
int read_length=0;
int count=0;
while((read_length=read(fd,buf,sizeof(buf)))>0)
{ count++;
buf[read_length]=‘\0‘;
printf("%s\n read %d ",buf,count);
}
printf("count=%d\n",count);
if(read_length<0)
err-quit("error of read");
close(fd);
return 0;
#include "unp.h"
#include <time.h>
int main(int argc,char *argv[])
{
int listenfd=Socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in servaddr;
servaddr.sin_family=AF_INET;
inet_pton(AF_INET,"0.0.0.0",&servaddr.sin_addr);
servaddr.sin_port=htons(13);
Bind(listenfd,(SA*)&servaddr,sizeof(servaddr));
Listen(listenfd,10);
time_t ticks;
int i;
char buf[1024];
for(;;)
{
int client_fd=accept(listenfd,NULL,0);
ticks=time(NULL);
snprintf(buf,sizeof(buf),"%.24s\r\n",ctime(&ticks));
for(i=0;i<strlen(buf);++i)
Write(client_fd,&buf[i],1);
Close(client_fd);
//Close(listenfd);
}
return 0;
}
~
标签:
原文地址:http://www.cnblogs.com/zengyiwen/p/5755210.html