#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <strings.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/un.h>
#include <linux/in.h>
#define N 100
/*
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
void FD_CLR(int fd, fd_set *set);
int FD_ISSET(int fd, fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);
*/
int main(void)
{
int sokfd;
int connfd;
struct sockaddr_in sev_sockaddr;
struct sockaddr_in client_sockaddr;
fd_set readfds;
fd_set readfdstemp;
int nfds;
int i=0;
int recvn=0;
char buf[N];
int client_sockaddr_len=sizeof(client_sockaddr);
if(( sokfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("scoket");
exit(-1);
}
bzero(&sev_sockaddr,sizeof(sev_sockaddr));
sev_sockaddr.sin_family=AF_INET;
sev_sockaddr.sin_port=htons(9000);
sev_sockaddr.sin_addr.s_addr=inet_addr("192.168.1.100");
if(bind(sokfd,(struct sockaddr*)&sev_sockaddr,sizeof(sev_sockaddr))==-1)
{
perror("bind");
exit(-1);
}
listen(sokfd,5);
struct timeval timeo={5,0};
FD_ZERO(&readfds);
FD_SET(sokfd,&readfds);
nfds=sokfd;
while(1)
{
//FD_ZERO(&readfds);
//FD_SET(sokfd,&readfds);
readfdstemp=readfds;
//timeo={5,0};
timeo.tv_sec=5;
timeo.tv_usec=0;
/*************************************************************************
timeout is an upper bound on the amount of time elapsed before select()
returns. If both fields of the timeval stucture are zero, then
select() returns immediately. (This is useful for polling.) If time鈥? out is NULL (no timeout), select() can block indefinitely.
************************************************************************/
/*************************************************************************
On success, select() and pselect() return the number of file descrip鈥? tors contained in the three returned descriptor sets (that is, the
total number of bits that are set in readfds, writefds, exceptfds)
which may be zero if the timeout expires before anything interesting
happens. On error, -1 is returned, and errno is set appropriately; the
sets and timeout become undefined, so do not rely on their contents
after an error.
*********************************************************************/
int ret=100000;
if((ret=select(nfds+1,&readfdstemp,NULL,NULL,&(timeo)))==-1)
{
perror("select");
exit(-1);
}
printf("time :%d\n",ret);
if(ret>0)
{
for(i=0;i<nfds+1;i++)
{
if(FD_ISSET(i,&readfdstemp))
{
if(i==sokfd)
{
connfd=accept(sokfd,(struct sockaddr*)&client_sockaddr,&client_sockaddr_len);
nfds=(nfds>connfd)?nfds:connfd;
FD_SET(connfd,&readfds);
}
else
{
bzero(buf,sizeof(buf));
recvn=recv(i,buf,10,0);
if(recvn==0)
{
close(i);
FD_CLR(i,&readfds);
break;
}
printf("%s\n",buf);
}
}
}
}
else
{
printf("the net is timeout...\n");
}
}
}
本文详细介绍了TCP/IP协议栈及其在网络编程中的应用,重点阐述了socket编程接口的使用方法,包括创建socket、绑定地址、监听连接、接受客户端连接、发送接收数据等关键步骤,同时提供了实际案例演示。
2670

被折叠的 条评论
为什么被折叠?



