当前位置: 首页>>代码示例>>C++>>正文


C++ Socket函数代码示例

本文整理汇总了C++中Socket函数的典型用法代码示例。如果您正苦于以下问题:C++ Socket函数的具体用法?C++ Socket怎么用?C++ Socket使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Socket函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

int
main(int argc, char **argv)
{
	int					ret, i, connfd;
	struct sockaddr_in	cliaddr, servaddr;
    socklen_t clilen, addrlen;
	void				sig_int(int);
    pthread_t tid;
    struct Thread *arg;

    if (argc != 3)
        err_quit("Usage: %s <port> <#threads>", basename(argv[0]));

    nthreads = atoi(argv[2]);

    if ((pThread = calloc(nthreads, sizeof(struct Thread))) == NULL)
        err_sys("calloc error");

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(atoi(argv[1]));

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);
    addrlen = sizeof(struct sockaddr_in);

    for (i = 0; i < nthreads; i++) {
        arg = pThread + i;
        arg->id = i;
        if ((ret = pthread_create(&tid, NULL, &mode_doit, (void *)arg)) != 0) {
            errno = ret;
            perror("pthread_create error");
            exit(1);
        }
    }

    Signal(SIGINT, sig_int);

    iput = iget = 0;
    for (;;) {
        clilen = addrlen;
        if ((connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen)) < 0)
            err_sys("accept error");

        if ((ret = pthread_mutex_lock(&mlock)) != 0) {
            errno = ret;
            perror("pthread_mutex_lock error");
            exit(1);
        }
        clifd[iput] = connfd;
        if (++iput == MAXNCLI)
            iput = 0;
        if (iput == iget)
            err_quit("iput = iget = %d\n", iput);
        if ((ret = pthread_cond_signal(&cond)) != 0) {
            errno = ret;
            perror("pthread_cond_signal error");
            exit(1);
        }
        if ((ret = pthread_mutex_unlock(&mlock)) != 0) {
            errno = ret;
            perror("pthread_mutex_unlock error");
            exit(1);
        }
    }
}
开发者ID:GongCun,项目名称:UNIX_Network_Programming_3thEd_Volume1,代码行数:70,代码来源:mode_serv08.c

示例2: main

int main()
{
    int Listenfd,connfd;
    socklen_t clilen;
    struct sockaddr_in cliaddr, servaddr;
    int val,len;
    pthread_t recv_thread, send_thread,getinfo_thread; 
    int res;

    Listenfd = Socket(AF_INET,SOCK_STREAM,0);

    memset(&servaddr,0,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port =  htons(SERV_PORT);
    
    Bind(Listenfd,(SA*)&servaddr,sizeof(servaddr));
    Listen(Listenfd,LISTENQ);
    

    for( ; ;){
    
        
        val = 3000;
        len = sizeof(int);
        Setsockopt(Listenfd, SOL_SOCKET, SO_RCVBUF,(void *)&val, len);
        
             
        clilen = sizeof(cliaddr);
        connfd = Accept(Listenfd,(SA*)&cliaddr,&clilen);
            
        val = 1;
        len = sizeof(int);
        Setsockopt(connfd, SOL_SOCKET, SO_DEBUG,(void *)&val, len);
        
        res = pthread_create(&getinfo_thread, NULL, get_info, (void *)(&connfd));  
        if (res != 0)  
        {  
            perror("Thread creation failed!");  
            exit(EXIT_FAILURE);  
        } 
                  
        res = pthread_create(&recv_thread, NULL, recv_function, (void *)(&connfd));  
        if (res != 0)  
        {  
            perror("Thread creation failed!");  
            exit(EXIT_FAILURE);  
        }  
        
        res = pthread_create(&send_thread, NULL, send_function, (void *)(&connfd));  
        if (res != 0)  
        {  
            perror("Thread creation failed!");  
            exit(EXIT_FAILURE);  
        }  


        
        //sleep(200);
        
        printf("close\n");
        //交由系统回收关闭文件描述符
        //Close(connfd);
    }
    return 0;
}
开发者ID:lybxin,项目名称:LNP,代码行数:66,代码来源:tcpserver.c

示例3: main

int
main(int argc, char **argv)
{
    int                 i,j, maxi, maxfd, listenfd, connfd, sockfd;
    int                 nready, client[FD_SETSIZE];
    ssize_t             n;
    fd_set              rset, allset;
    char                buf[MAXLINE];
    socklen_t           clilen;
    struct sockaddr_in  cliaddr, servaddr;

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(7746);

    Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

    Listen(listenfd, LISTENQ);

    maxfd = listenfd;           /* initialize */
    maxi = -1;                  /* index into client[] array */
    for (i = 0; i < FD_SETSIZE; i++)
        client[i] = -1;         /* -1 indicates available entry */
    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);
/* end fig01 */

/* include fig02 */
    for ( ; ; ) {
        rset = allset;      /* structure assignment */
        nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

        if (FD_ISSET(listenfd, &rset)) {    /* new client connection */
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef  NOTDEF
            printf("new client: %s, port %d\n",
                    Inet_ntop(AF_INET, &cliaddr.sin_addr, 4, NULL),
                    ntohs(cliaddr.sin_port));
#endif

            for (i = 0; i < FD_SETSIZE; i++)
                if (client[i] < 0) {
                    client[i] = connfd; /* save descriptor */
                    break;
                }
            if (i == FD_SETSIZE)
                err_quit("too many clients");

            FD_SET(connfd, &allset);    /* add new descriptor to set */
            if (connfd > maxfd)
                maxfd = connfd;         /* for select */
            if (i > maxi)
                maxi = i;               /* max index in client[] array */

            if (--nready <= 0)
                continue;               /* no more readable descriptors */
        }

        for (i = 0; i <= maxi; i++) {   /* check all clients for data */
            if ( (sockfd = client[i]) < 0)
                continue;
            if (FD_ISSET(sockfd, &rset)) {
                if ( (n = Read(sockfd, buf, MAXLINE)) == 0) {
                        /*4connection closed by client */
                    Close(sockfd);
                    FD_CLR(sockfd, &allset);
                    client[i] = -1;
                } else
                    for(j = 0; j<= maxi;j++) {
                        if ((sockfd = client[j]) > 0 && i != j && strlen(buf) > 0) { //像自己以外的客户端发送信息
                            Writen(sockfd, buf, n);
                        }
                    }

                    Writen(fileno(stdout), buf, n);

                if (--nready <= 0)
                    break;              /* no more readable descriptors */
            }
        }
    }
}
开发者ID:liu1s,项目名称:rubbish_store,代码行数:86,代码来源:chatserver.c

示例4: main

int
main(int argc, char **argv)
{
	int sock_fd,msg_flags;
	char readbuf[BUFFSIZE];
	struct sockaddr_in servaddr, cliaddr;
	struct sctp_sndrcvinfo sri;
	struct sctp_event_subscribe evnts;
	int stream_increment=1;
	socklen_t len;
	size_t rd_sz;

	if (argc == 2)
		stream_increment = atoi(argv[1]);
        sock_fd = Socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	Bind(sock_fd, (SA *) &servaddr, sizeof(servaddr));
	
/* include mod_serv06 */
	bzero(&evnts, sizeof(evnts));
	evnts.sctp_data_io_event = 1;
	evnts.sctp_association_event = 1;
	evnts.sctp_address_event = 1;
	evnts.sctp_send_failure_event = 1;
	evnts.sctp_peer_error_event = 1;
	evnts.sctp_shutdown_event = 1;
	evnts.sctp_partial_delivery_event = 1;
	evnts.sctp_adaptation_layer_event = 1;
	Setsockopt(sock_fd, IPPROTO_SCTP, SCTP_EVENTS,
		   &evnts, sizeof(evnts));

	Listen(sock_fd, LISTENQ);
	printf("Start waiting...\n");
	for ( ; ; ) {
		len = sizeof(struct sockaddr_in);
		rd_sz = Sctp_recvmsg(sock_fd, readbuf, sizeof(readbuf),
			     (SA *)&cliaddr, &len,
			     &sri,&msg_flags);
		if(msg_flags & MSG_NOTIFICATION) {	// 表示收到一個事件,而非一個資料
			print_notification(readbuf);
			continue;
		}
/* end mod_serv06 */
		if(stream_increment) {
			sri.sinfo_stream++;
			// getsockopt用在sctp有問題!!先跳過!
			// if(sri.sinfo_stream >= sctp_get_no_strms(sock_fd,(SA *)&cliaddr, len)) 
			if(sri.sinfo_stream >= 100)
				sri.sinfo_stream = 0;
		}
		Sctp_sendmsg(sock_fd, readbuf, rd_sz, 
			     (SA *)&cliaddr, len,
			     sri.sinfo_ppid,
			     sri.sinfo_flags,
			     sri.sinfo_stream,
			     0, 0);
	}
}
开发者ID:nightfly19,项目名称:renyang-learn,代码行数:62,代码来源:server.c

示例5: main

int
main (int argc,char* argv[])
{
  int i,maxi,listenfd,connfd,sockfd;
  int nready;
  ssize_t n;
  char line[MAXLINE];
  socklen_t clilen;
  struct pollfd client[OPEN_MAX];
  struct sockaddr_in cliaddr,servaddr;
  listenfd = Socket(AF_INET,SOCK_STREAM,0);
  bzero(&servaddr,sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);
  Bind(listenfd,(sockaddr*)&servaddr,sizeof(servaddr));
  Listen(listenfd,LISTENQ);
  client[0].fd = listenfd;
  client[0].events = POLLRDNORM;
  for (i=1;i<OPEN_MAX;++i)
  	client[i].fd = -1;//indicates avallable entry
  maxi=0; //max index int client[]
  for(;;)
  {
  	//nready = poll(client,maxi+1,INFTIM);
  	nready = poll(client,maxi+1,-1);
  	if(client[0].revents&POLLRDNORM)//new client connection
  	{
  		clilen = sizeof(cliaddr);
  		connfd = Accept(listenfd,(sockaddr*)&cliaddr,&clilen);
  		for (i=1; i<OPEN_MAX;++i)
  		{
  			if (client[i].fd<0)
  			{
           client[i].fd = connfd; //save descriptor
           break;
  			}
  		}
  		if (i == OPEN_MAX)
  			err_sys("too many clients");
  		client[i].events = POLLRDNORM;
  		if(i>maxi)
  			maxi = i; //max index in client[]
  		if(--nready<=0)
  			continue; //no more readable descriptors
  	}
  	for (i=1; i<=maxi; ++i)//check all clients for data
  	{
  		if((sockfd = client[i].fd)<0)
  			continue;;
  		if(client[i].revents&(POLLRDNORM|POLLERR))
  		{
  			if((n=readline(sockfd,line,MAXLINE))<0)
  			{
  				if(errno == ECONNRESET)
  				{//connection reset by client
  					Close(sockfd);
  					client[i].fd=-1;
  				}
  				else
  					err_sys("readline error");
  			}
  			else if(n==0)
  			{//connection closed by client
  				Close(sockfd);
  				client[i].fd=-1;
  			}
  			else
  				writen(sockfd,line,n);
  			if(--nready<=0)
  				break; //no more readable descriptors
  		}
  	}
  }

}
开发者ID:bonly,项目名称:exercise,代码行数:76,代码来源:20090207_srv_poll.cpp

示例6: if_init

void
if_init()
{
	struct hwa_info *hwa, *hwahead;
	struct sockaddr *sa;
	struct hostent *hptr;
	char *ptr;
	char **pptr;
	int i, j, prflag, n;
	struct arp_cache_entry cache_entry;

	memset(if_hwaddr, 0, sizeof(if_hwaddr));
	memset(if_sock, 0, sizeof(if_sock));
	if_size = 0;
	puts("<-- HW INFO -->");
	for (i = 0; i < NUM_VM; i++){
		sprintf(node_ip[i], "vm%d", i+1);
		hptr = gethostbyname(node_ip[i]);
		for (pptr = hptr->h_addr_list; *pptr != NULL; pptr++){
			Inet_ntop(hptr->h_addrtype, *pptr, node_ip[i], INET_ADDRSTRLEN);
		}
	}
	for (hwahead = hwa = Get_hw_addrs(); hwa != NULL; hwa = hwa->hwa_next) {
		printf("interface index = %d\n", (n = hwa->if_index));
		printf("%s :%s", hwa->if_name,
				((hwa->ip_alias) == IP_ALIAS) ? " (alias)\n" : "\n");

		if ((hwa->ip_alias) != IP_ALIAS) {
			if_size++;
		}
		if ((sa = hwa->ip_addr) != NULL) {
			printf("\tIP addr = %s\n", Sock_ntop_host(sa, sizeof(*sa)));

			if (hwa->if_haddr != NULL) {
				if (strcmp(hwa->if_haddr, if_hwaddr[my_index])
						== 0 && (hwa->ip_alias) == IP_ALIAS) {
					insert_local_hw_cache(Sock_ntop_host(sa, sizeof(*sa)));
				}
			}
		}
		// get canonical ip
		if (strcmp(hwa->if_name, "eth0") == 0) {
			sprintf(my_ip, "%s", Sock_ntop_host(sa, sizeof(*sa)));

			my_index = hwa->if_index;
			for (my_vm = 0; my_vm < NUM_VM; my_vm++) {
				if (strcmp(my_ip, node_ip[my_vm]) == 0) {
					my_vm++;
					break;
				}
			}
		}

		prflag = i = 0;
		do {
			if (hwa->if_haddr[i] != '\0') {
				prflag = 1;
				break;
			}
		} while (++i < IF_HADDR);

		if (prflag) {
			printf("\tHW addr = ");
			for (i = 0; i < IF_HADDR; i++) {
				if_hwaddr[n][i] = hwa->if_haddr[i];
				printf("%02x ", (int) if_hwaddr[n][i] & 0xff);
			}
			puts("");
		}
	}
	// printf("***info: number of interfaces -- %d\n***", if_size);
	// Create PF_PACKET socket for etho0
	if_sockfd = Socket(AF_PACKET, SOCK_RAW, htons(ARP_PROTOCOL));

	addr.sll_family = PF_PACKET;
	addr.sll_protocol = htons(ARP_PROTOCOL);
	addr.sll_ifindex = my_index;
	addr.sll_hatype = ARPHRD_ETHER;
	addr.sll_pkttype = PACKET_HOST;
	addr.sll_halen = ETH_ALEN;

	for (j = 0; j < ETH_ALEN; j++){
		addr.sll_addr[j] = if_hwaddr[my_index][j];
	}

	Bind(if_sockfd, (SA *)&addr, sizeof(struct sockaddr_ll));
	maxfd= (maxfd, if_sockfd);
	insert_local_hw_cache(my_ip);
	// puts("if_init done\n");
	puts("");
}
开发者ID:fanyang88,项目名称:ARP_protocol,代码行数:91,代码来源:arp.c

示例7: main

int main(int argc, char** argv)
{
    int i, maxi, maxfd, listenfd,connfd, sockfd;
    int nready;
    ssize_t n;
    char buf[MAXLINE];
    socklen_t clilen;
    struct pollfd client[OPEN_MAX];
    struct sockaddr_in cliaddr, servaddr;

    fprintf(stdout, "main\n");
    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    Bind(listenfd, (SA*) &servaddr, sizeof(servaddr));

    fprintf(stdout,"begin listen");
    Listen(listenfd, LISTENQ);
    client[0].fd = listenfd;
    client[0].events = POLLRDNORM;
    for(i = 0; i != OPEN_MAX; ++i)
    {
        client[i].fd = -1;
    }
    fprintf(stdout,"begin loop");
    maxi = 0;
    for(; ; ){
        fprintf(stdout,"begin poll");

        nready = Poll(client, maxi + 1, INFTIM);
        if(client[0].revents & POLLRDNORM){
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA*) & cliaddr, & clilen);
            fprintf(stdout,"accept success");

            for(i = 1; i != OPEN_MAX; ++i)
            {
                if(client[i].fd < 0)
                {
                    client[i].fd = connfd;
                    break;
                }
            }
            if(i == OPEN_MAX)
                err_quit("too many clients");
            client[i].events = POLLRDNORM;
            if(i > maxi)
                maxi = i;
            if(--nready <= 0)
                continue;
        }
        for(i = 1; i <= maxi; ++i){

            if( (sockfd = client[i].fd) <0)
                continue;
            if(client[i].revents & (POLLRDNORM | POLLERR)){
                if((n = read(sockfd, buf, MAXLINE)) < 0){
                    if(errno == ECONNRESET){
                        Close(sockfd);
                        client[i].fd = -1;
                    }
                    else
                    {
                        err_sys("read error");
                    }
                }else if(n == 0)
                {
                    Close(sockfd);
                    client[i].fd =-1;
                }
                else{
                    Writen(sockfd, buf, n);
                }
               if(--nready <=0)break;
            }
        }
    }
}
开发者ID:yulingjie,项目名称:Net,代码行数:82,代码来源:tcpservpoll.c

示例8: main

int
main(int argc, char **argv)
{
        Signal( SIGINT, sigInt);
	int			i, maxi, maxfd, listenfd, connfd, sockfd;
	int			nready, client[FD_SETSIZE];
	ssize_t			n;
	fd_set			rset, allset;
	char			buf[MAXLINE];
	socklen_t		clilen;
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

        /* SO_REUSEADDR allows a new server to be started
         * on the same port as an existing server that is
         * bound to the wildcard address, as long as each
         * instance binds a different local IP address.
         * This is common for a site hosting multiple HTTP
         * servers using the IP alias technique */
        int reuseaddr_on = 1;
        if( setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR,
                &reuseaddr_on, sizeof( reuseaddr_on)) < 0)
        {
            // log
        }

	Bind( listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen( listenfd, LISTENQ);

	maxfd = listenfd;			/* initialize */
	maxi = -1;				/* index into client[] array */
	for ( i = 0; i < FD_SETSIZE; ++i)
		client[i] = -1;			/* -1 indicates available entry */
	FD_ZERO( &allset);
	FD_SET( listenfd, &allset);

	for ( ; ; ) {
		rset = allset;                  /* structure assignment */
                
                /* select waits for something to happen: either the establishment
                 * of a new client connection or the arrival of data, a FIN,
                 * or an RST on an existing connection */
		nready = Select( maxfd + 1, &rset, NULL, NULL, NULL);

		if ( FD_ISSET( listenfd, &rset)) {	/* new client connection */
                    
                    /* simulate busy server */
                    printf( "listening socket readable -> sleep(5)\n");
                    sleep(5);

                    /* If the listening socket is readable, a new connection has been 
                     * established. We call accept and update our data structures
                     * accordingly. We use the first unused entry in the client array
                     * to record the connected socket. The number of ready descriptors
                     * is decremented, and if it is 0, we can avoid the next for loop.
                     * This lets us use the return value from select to avoid checking
                     * descriptors that are not ready.*/
			clilen = sizeof( cliaddr);
                        printf( "accept called\n"); fflush( stdout);
			connfd = accept( listenfd, ( SA *) &cliaddr, &clilen);
                        printf( "accept returned, connfd=%d\n", connfd); fflush( stdout);

			for ( i = 0; i < FD_SETSIZE; ++i)
				if (client[i] < 0) {
					client[i] = connfd;	/* save descriptor */
					break;
				}
			if ( i == FD_SETSIZE)
				err_quit( "too many clients");

			FD_SET( connfd, &allset);	/* add new descriptor to set */
			if ( connfd > maxfd)
				maxfd = connfd;		/* for select */
			if ( i > maxi)
				maxi = i;		/* max index in client[] array */

			if ( --nready <= 0)
				continue;		/* no more readable descriptors */
		}

		for ( i = 0; i <= maxi; ++i) {	/* check all clients for data */
                    
                    /* A test is made for each existing client connection as to whether
                     * or not its descriptor is in the descriptor set returned by select.
                     * If so, a line is read from the client and echoed back to the client.
                     * If the client closes the connection, read returns 0 and we update
                     * our data structures accordingly. We never decrement the value
                     * of maxi, but we could check for this possibility each time a client
                     * closes its connection.*/
			if ( ( sockfd = client[i]) < 0)
				continue;
			if ( FD_ISSET( sockfd, &rset)) {
				if ( ( n = Read( sockfd, buf, MAXLINE)) == 0) {
//.........这里部分代码省略.........
开发者ID:bharathvu,项目名称:unix_networking_projects,代码行数:101,代码来源:main.c

示例9: benchcore

void benchcore(const char *host,const int port,const char *req)  
{  
    int rlen;  
    char buf[1500];  
    int s,i;  
    struct sigaction sa;  
  
    /*安装信号 */  
    /* setup alarm signal handler */  
    sa.sa_handler = alarm_handler;  
    sa.sa_flags = 0;  
    if(sigaction(SIGALRM,&sa,NULL))  
        exit(3);  
  
    /* 设置闹钟函数 */  
    alarm(benchtime);  
  
    rlen = strlen(req);  
  
nexttry:  
    while(1){  
        /* 收到信号则 timerexpired = 1 */  
        if(timerexpired)  
        {  
            if(failed > 0)  
            {  
                /* fprintf(stderr,"Correcting failed by signal\n"); */  
                failed--;  
            }  
            return;  
        }  
        /* 建立 socket, 进行 HTTP 请求 */  
        s = Socket(host,port);  
        if(s < 0)  
        {  
            failed++;  
            continue;  
        }  
        if(rlen!=write(s,req,rlen))  
        {  
            failed++;  
            close(s);  
            continue;  
        }  
        /* HTTP 0.9 的处理 */  
        if(http10==0)  
            /* 如果关闭不成功 */  
            if(shutdown(s,1))  
            {  
                failed++;  
                close(s);  
                continue;  
            }  
  
        /* -f 选项时不读取服务器回复 */  
        if(force == 0)  
        {  
            /* read all available data from socket */  
            while(1)  
            {  
                if(timerexpired) break;  
                i = read(s,buf,1500);  
                /* fprintf(stderr,"%d\n",i); */  
                if(i<0)  
                {  
                    failed++;  
                    close(s);  
                    goto nexttry;  
                }  
                else  
                    if(i == 0) break;  
                    else bytes+=i;  
            }  
        }  
        if(close(s))  
        {  
            failed++;  
            continue;  
        }  
        speed++;  
    }  
}  
开发者ID:sanmubai,项目名称:cpp,代码行数:82,代码来源:webbench.c

示例10: main

int
main(int argc, char *argv[])
{
    int				c, lopt=0;
    char			*ptr, localname[1024], *localport;
    struct addrinfo	*aip;
    /* end main1 */

    /* include main2 */
    opterr = 0;		/* don't want getopt() writing to stderr */
    while ( (c = getopt(argc, argv, "0i:l:v")) != -1)
    {
        switch (c)
        {

        case '0':
            zerosum = 1;
            break;

        case 'i':
            device = optarg;			/* pcap device */
            break;

        case 'l':			/* local IP address and port #: a.b.c.d.p */
            if ( (ptr = strrchr(optarg, '.')) == NULL)
                usage("invalid -l option");

            *ptr++ = 0;					/* null replaces final period */
            localport = ptr;			/* service name or port number */
            strncpy(localname, optarg, sizeof(localname));
            lopt = 1;
            break;

        case 'v':
            verbose = 1;
            break;

        case '?':
            usage("unrecognized option");
        }
    }
    /* end main2 */
    /* include main3 */
    if (optind != argc-2)
        usage("missing <host> and/or <serv>");

    /* 4convert destination name and service */
    aip = Host_serv(argv[optind], argv[optind+1], AF_INET, SOCK_DGRAM);
    dest = aip->ai_addr;		/* don't freeaddrinfo() */
    destlen = aip->ai_addrlen;

    /*
     * Need local IP address for source IP address for UDP datagrams.
     * Can't specify 0 and let IP choose, as we need to know it for
     * the pseudoheader to calculate the UDP checksum.
     * If -l option supplied, then use those values; otherwise,
     * connect a UDP socket to the destination to determine the right
     * source address.
     */
    if (lopt)
    {
        /* 4convert local name and service */
        aip = Host_serv(localname, localport, AF_INET, SOCK_DGRAM);
        local = aip->ai_addr;		/* don't freeaddrinfo() */
        locallen = aip->ai_addrlen;
    }
    else
    {
        int s;
        s = Socket(AF_INET, SOCK_DGRAM, 0);
        Connect(s, dest, destlen);
        /* kernel chooses correct local address for dest */
        locallen = sizeof(locallookup);
        local = (struct sockaddr *)&locallookup;
        Getsockname(s, local, &locallen);
        if (locallookup.sin_addr.s_addr == htonl(INADDR_ANY))
            err_quit("Can't determine local address - use -l\n");
        close(s);
    }

    open_output();		/* open output, either raw socket or libnet */

    open_pcap();		/* open packet capture device */

    setuid(getuid());	/* don't need superuser privileges anymore */

    Signal(SIGTERM, cleanup);
    Signal(SIGINT, cleanup);
    Signal(SIGHUP, cleanup);

    test_udp();

    cleanup(0);
}
开发者ID:as2120,项目名称:ZAchieve,代码行数:94,代码来源:main.c

示例11: main

int main(int argc,char* argv[])
{
    char *str = new char[MAXSIZE],*p;
    int Port_BDS = atoi(argv[2]);
    int Port_FC = atoi(argv[3]);

    sockfd_BDS = Socket();
    sockfd_FC = Socket();

    struct sockaddr_in servself_addr,client_addr,servBDS_addr;
    struct hostent *host;
    int nread;
    socklen_t len;

    Bind(sockfd_FC,servself_addr,Port_FC);
    Listen(sockfd_FC,5);
    printf("The FS is listening\n");

    bzero(&servBDS_addr,sizeof(servBDS_addr));
    servBDS_addr.sin_family = AF_INET;
    host = gethostbyname(argv[1]);
    memcpy(&servBDS_addr.sin_addr.s_addr,host->h_addr,host->h_length);
    servBDS_addr.sin_port = htons(Port_BDS);
    connect(sockfd_BDS,(struct sockaddr*)&servBDS_addr,sizeof(servBDS_addr));

    initial();
    while (1)
    {
        len = sizeof(client_addr);
        client_sockfd = accept(sockfd_FC,(struct sockaddr *) &client_addr, &len);
        printf("Connect successfully\n");

        bzero(SendToFC,sizeof(SendToFC));
        strcat(SendToFC,CurrentInode.Name);
        strcat(SendToFC," $ ");
        Write(client_sockfd,SendToFC,strlen(SendToFC));
        while (1)
        {
            bzero(ReceFromFC,sizeof(ReceFromFC));
           int n = Read(client_sockfd,ReceFromFC,MAXSIZE);
            Write(STDOUT_FILENO,ReceFromFC,strlen(ReceFromFC));
           // Show(CurrentInode,CurrentData);
            strcpy(str,ReceFromFC);
            p = str;
            str = strtok(str," \n");
            if (0 == strcmp(str,"f")) Format();
            else if (0 == strcmp(str,"mk"))  /*Create a file*/ 
            {
                str = strtok(NULL," \n");
                Createfile(str,0);
            }
            else if (0 == strcmp(str,"mkdir")) /*Create a folder*/
            {
                str = strtok(NULL," \n");
                Createfile(str,1);
            }
            else if (0 == strcmp(str,"rm")) /*Remove a file*/
            {
                str = strtok(NULL," \n");
                 Removefile(str,0);
            }
            else if (0 == strcmp(str,"cd")) /*Change path*/
            {
                str = strtok(NULL," \n");
                Changedir(str);
                HandleError("cdok!\n");
            }
            else if (0 == strcmp(str,"rmdir")) 
            {
                str = strtok(NULL," \n"); /*Remove a folder*/
                Removefile(str,1);
            }
            else if (0 == strcmp(str,"ls")) 
            {
                str = strtok(NULL," \n");
                List(str);
            }
            else if (0 == strcmp(str,"cat")) /*Catch a file*/ 
            {
                str = strtok(NULL," \n");
                Catchfile(str);
                printf("Catch ok!\n");
            }
            else if (0 == strcmp(str,"w")) 
            {
                str = strtok(NULL,"\n");
                WriteData(str);
            }
            else if (0 == strcmp(str,"a")) 
            {
                str = strtok(NULL,"\n");
                Append(str);
            }
            else if (0 == strcmp(str,"exit")) 
                Exit();
            else 
            {
                HandleError("2:Unavailable command\n");
            }
            bzero(SendToFC,sizeof(SendToFC));
//.........这里部分代码省略.........
开发者ID:lxyyxl638,项目名称:OS_Prj2,代码行数:101,代码来源:FS.cpp

示例12: main

int
main(int argc, char **argv)
{

  /*
 int sockfd;
  //sockaddr_in for the internet family
  struct sockaddr_in servaddr;
  //struct addrinfo hints;
  struct addrinfo *res;
  //const char *result = argv[1];
  //int port = atoi(argv[2]);
  
  if(argc != 3)
    err_quit("usage: tcpcli <IPAddress>");

  //
  sockfd = Socket(AF_INET, SOCK_STREAM, 0);

   

  if(sockfd != -1)
    {
      //printf("socket created\n");
    } else {
    printf("socket failed\n");
  }

  //convert names.
  //hints->ai_flags = AI_PASSIVE;
  //puts an appropriate number of zero bytes in area pointed to by &servaddr
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(atoi(argv[2])); //SERV_PORT to *argv[2]
 

  getaddrinfo(argv[1], argv[2], NULL, &res);

  Bind(sockfd, (SA *) &servaddr, sizeof(servaddr));
  // Bind(sockfd, , sizeof(res));

  

  Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));


  str_cli(stdin, sockfd);

  close(sockfd);
  */

  struct addrinfo hints, *res;
  int sockfd;

  memset(&hints, 0, sizeof hints);

  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;

  getaddrinfo(argv[1], argv[2], &hints, &res);

  sockfd = Socket(res->ai_family, res->ai_socktype, res->ai_protocol);

  //Bind(sockfd, res->ai_addr, res->ai_addrlen);
  
  Connect(sockfd, res->ai_addr, res->ai_addrlen);

  str_cli(stdin, sockfd);

  close(sockfd);

  exit(0);
}
开发者ID:Rokuren,项目名称:OldCode,代码行数:73,代码来源:client.c

示例13: main

int main(int argc, char** argv) {

	char rbuf[MAXBUF];							// transmitter and receiver buffers
	SOCKET s; 											// socket
	struct in_addr sIPaddr;					// server IP address structure
	struct sockaddr_in saddr; 			// server address structure
	uint16_t tport_n, tport_h;			// server port number by htons()
	char *filename;
	FILE* fp;
	uint32_t fileBytesN, fileBytes, nNext, nLeft;
	ssize_t nread, nwritten;
	
	XDR xdrs_in;											// Input XDR stream 
	XDR xdrs_out;											// Output XDR stream 
	FILE* stream_socket_r;						// FILE stream for reading from the socket
	FILE* stream_socket_w;						// FILE stream for writing to the socket
	call_msg reqMessage;
	response_msg resMessage;
	
	/* Check number of arguments */
	checkArg(argc, 4);
	
	prog_name = argv[0];
	
	/* Set IP address */
	setIParg(argv[1], &sIPaddr);
	
	/* Set port number  */
	tport_n = setPortarg(argv[2], &tport_h);
	
	/* Save the file to request */
	filename = argv[3];
	
	/* Create the socket */
	fprintf(stdout, "Creating the socket...\n");
	s = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	fprintf(stdout, "- OK. Socket fd: %d\n", s);
	
	/* Prepare server address structure */
	saddr.sin_family = AF_INET;
	saddr.sin_port = tport_n;
	saddr.sin_addr = sIPaddr;

	/* Send connection request */
	fprintf(stdout, "Connecting to target address...\n");
	Connect(s, (struct sockaddr*) &saddr, sizeof(saddr));
	fprintf(stdout, "- OK. Connected to ");
	showAddress(&saddr);
	
	/* Open FILE reading stream and bind it to the corresponding XDR stream */
	stream_socket_r = fdopen(s, "r");
	if (stream_socket_r == NULL) {
		fprintf(stderr, "---ERROR. fdopen() failed.\n");
		return 1;
	}
	xdrstdio_create(&xdrs_in, stream_socket_r, XDR_DECODE);

	/* Open FILE writing stream and bind it to the corresponding XDR stream */
	stream_socket_w = fdopen(s, "w");
	if (stream_socket_w == NULL) {
		fprintf(stderr, "---ERROR. fdopen() failed.\n");
		xdr_destroy(&xdrs_in);
		fclose(stream_socket_r);
		return 1;
	}
	xdrstdio_create(&xdrs_out, stream_socket_w, XDR_ENCODE);
	
	while(1) {
		/* Send a file request */
		reqMessage.ctype = GET;
		reqMessage.call_msg_u.filename = filename;
		if (!xdr_call_msg(&xdrs_out, &reqMessage)) {
			fprintf(stdout, "- ERROR sending GET message.\n");
			break;
		}
		fflush(stream_socket_w);
	
		/* Receive a message */
		if (!xdr_response_msg(&xdrs_in, &resMessage)) {
			fprintf(stdout, "- ERROR. Response xdr_response_msg() failed.\n");
			break;
		}
		fprintf(stdout, "- Received response.\n");
		
		
		if (resMessage == OK) {
				
			fprintf(stdout, "- File received: %s\n", filename);
			
			// Read the file size
			nread = read(s, (void*)&fileBytesN, sizeof(uint32_t));

			fileBytes = ntohl(fileBytesN);
			fprintf(stdout, "- File size: %u\n", fileBytesN);

			// Received and write file
			fp = Fopen(filename, "wb");
			nLeft = fileBytes;
			while(nLeft > 0) {
				
//.........这里部分代码省略.........
开发者ID:ThomasVitale,项目名称:Distributed-Programming-1,代码行数:101,代码来源:client_main.c

示例14: getnrd

/* getnrd 
   
   write command to wthd and read response
   IPv4 version
 
*/
int getnrd(unsigned char *data, int *mdat, struct cmd *pcmd) {
    int                  sockfd, n, len;
    char                 sendline[MAXLINE] = "1";
    struct sockaddr_in   servaddr;

    struct in_addr **pptr, *addrs[2];
    struct hostent *hp;
    struct servent *sp;
	
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;

    /* hostname or ipaddress */
    if (inet_pton(AF_INET, pcmd->hostname, &servaddr.sin_addr) == 1) {
	  addrs[0] = &servaddr.sin_addr;
	  addrs[1] = NULL;
	  pptr = &addrs[0];
    } else if ( (hp = gethostbyname(pcmd->hostname)) != NULL) {
	  pptr = (struct in_addr **) hp->h_addr_list;
    } else {
	  werrno = h_errno;
	  syslog(LOG_INFO,"hostname error for %s: %s", 
		 pcmd->hostname, hstrerror(h_errno));
	  return (-1);
	  }
    /* port number or service name */
    if ( (n = atoi(pcmd->port)) > 0)
	  servaddr.sin_port = htons(n);
    else if ( (sp = getservbyname(pcmd->port, "tcp")) != NULL)
	  servaddr.sin_port = sp->s_port;
    else {
	  syslog(LOG_INFO,"getservbyname error for %s", pcmd->port);
	  werrno = ENET;
	  return(-1);
    }
    /* connect to server */
    for ( ; *pptr != NULL; pptr++) {
      if ( ( sockfd = Socket(AF_INET, SOCK_STREAM, 0)) == -1 )
	return(-1);

      memmove(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
      Sock_ntop((SA *) &servaddr, sizeof(servaddr));
	  
      if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == 0)
	break; /* success */

      werrno = errno;
      syslog(LOG_INFO, "getnrd: connect error: %s",
	     strerror(werrno));
      return(-1);

      close(sockfd);
    }
    if (*pptr == NULL ) {
      syslog(LOG_INFO, "unable to connect");
      werrno = ENET;
      return(-1);
    }

    /* write command to server */
    snprintf(sendline, sizeof(sendline), "%d\r\n", (*pcmd).command);
    if ( Writen(sockfd, sendline, 1) == -1 )
      return(-1);
    
    /* read response. rwstephens unp p.10 */
    while ( ( n = read(sockfd, data, MAXBUFF)) > 0) {
      data[n] = 0;
    }

    /* code doesn't work. why?
       if (Readline(sockfd, line, MAXLINE) == 0)
       err_quit("getnrd: server terminated prematurely");
    */

    len = wstrlen(data);
    *mdat = len;
	
    return(0);
}
开发者ID:BackupTheBerlios,项目名称:wth-svn,代码行数:85,代码来源:net.c

示例15: main

int main(int argc, char **argv){
	int res = 0;
	struct timeval tv1, tv2;
	char *directory = NULL;

	if (argc != 3)
		err_quit("usage: client <IPaddress> <file dir>");
	serverip = argv[1];
	directory = argv[2];

	gettimeofday(&tv1, NULL);

	sockfd4pox = get_udp_socket(QUICK_PORT);// channel with POX

	bzero(&servaddrfp, sizeof(servaddrfp));
	servaddrfp.sin_family = AF_INET;
	servaddrfp.sin_port = htons(SERV_PORT+1);
	Inet_pton(AF_INET, argv[1], &servaddrfp.sin_addr);
	sockfd2serverfp = Socket(AF_INET, SOCK_DGRAM, 0);
	// Connect(sockfd2serverfp, (SA *)&servaddrfp, sizeof(servaddrfp));

	struct timeval tv;
	tv.tv_sec = 1;
	tv.tv_usec = 0;// 
	setsockopt(sockfd2serverfp, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
	int a = 65535;
	Setsockopt(sockfd2serverfp, SOL_SOCKET, SO_SNDBUF, &a, sizeof(int));
	Setsockopt(sockfd2serverfp, SOL_SOCKET, SO_RCVBUF, &a, sizeof(int));


#ifdef USE_UDP
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
	sockfd2server = Socket(AF_INET, SOCK_DGRAM, 0);
#else
	sockfd2server = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT); //
	Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	Connect(sockfd2server, (SA *) &servaddr, sizeof(servaddr));
	Setsockopt(sockfd2server, SOL_SOCKET, SO_SNDBUF, &a, sizeof(int));
#endif
	// start 
	start_backup();

	uploadDir(directory);
	// uploadDir_recur(directory);

	gettimeofday(&tv2, NULL);
	printf("Time cost = %lfms\n",(tv2.tv_sec-tv1.tv_sec)*1000.0+(tv2.tv_usec-tv1.tv_usec)/1000.0);

    /* Upload complete, tell server to sync data to SDN controller
     * Need a alg(by dedu ratio) to control this sync
     */
    end_backup();


	close(sockfd4pox);
	
	// shutdown(sockfd2server, SHUT_WR);
	// shutdown(sockfd2serverfp, SHUT_WR);
	close(sockfd2serverfp);
	close(sockfd2server);
	exit(0);
}
开发者ID:vonzhou,项目名称:SdnBasedDeduplication,代码行数:70,代码来源:client07.c


注:本文中的Socket函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。