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


C++ setsockopt函数代码示例

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


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

示例1: perror

void *Switch_Control::TCP_Accept_Control_thread(void *arg)
{

	Switch_Control *this0 = (Switch_Control*)arg;

	int BUFFER_SIZE = 4096;
	struct sockaddr_in s_addr;
	int sock;
	socklen_t addr_len;


	if ( (sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))  == -1) {
		perror("socket");
		fflush(stderr);
		LOG_ERROR("ERROR  SWM : Create Socket ERROR \n");
		return NULL;
	} else
		printf("create socket.\n\r");
	fflush(stdout);

	memset(&s_addr, 0, sizeof(struct sockaddr_in));
	s_addr.sin_family = AF_INET;

	s_addr.sin_port = htons(this0->m_iMsiPort);


	s_addr.sin_addr.s_addr = inet_addr(this0->SW_ip.c_str());//INADDR_ANY;

	int optval = 1;
	if ((setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(int))) == -1)
	{
		close(sock);
		LOG_ERROR("ERROR  SWM : Set Socket ReUSED ERROR \n");
		return NULL;
	}

	if ( (bind(sock, (struct sockaddr*)&s_addr, sizeof(s_addr))) == -1 ) {
		perror("bind");
		fflush(stderr);
		LOG_ERROR("ERROR  SWM : Bind Socket ERROR \n");
		return NULL;
	}else
		printf("bind address to socket.\n\r");
	fflush(stdout);

	if(listen(sock,10)<0)
	{
		perror("listen");
		fflush(stderr);
		LOG_ERROR("ERROR  SWM : Listen Socket ERROR \n");
		return NULL;
	}

	int accept_fd = -1;
	struct sockaddr_in remote_addr;
	memset(&remote_addr,0,sizeof(remote_addr));

	this0->m_MsiacceptSocket = -1;
	
	while( 1 )
	{  
		
	    socklen_t sin_size = sizeof(struct sockaddr_in); 
		if(( accept_fd = accept(sock,(struct sockaddr*) &remote_addr,&sin_size)) == -1 )  
         {  
             	printf( "Accept error!\n");  
				fflush(stdout);
                //continue;  
	     }  
         printf("Received a connection from %s\n",(char*) inet_ntoa(remote_addr.sin_addr));  

		fflush(stdout);

		if(this0->m_MsiacceptSocket != -1)
		{
			//需要释放之前的链接
		}
		this0->m_MsiacceptSocket = accept_fd;

		//将socket加入队列
		pthread_mutex_lock(&this0->m_lockerQuesocket);
		this0->m_QueSokcet.push(accept_fd);
		pthread_mutex_unlock(&this0->m_lockerQuesocket);
		
		pthread_t tcp_recv_thread1;
		pthread_create(&tcp_recv_thread1, NULL, Parse_recv_MSI_thread, this0);
		pthread_detach(tcp_recv_thread1);
		

	}


}
开发者ID:yyd01245,项目名称:BBCV_SM_project,代码行数:93,代码来源:Switch_Control.cpp

示例2: identd

static int identd(char *username)
{
        int sok, read_sok, len;
        char *p;
        char buf[256];
        char outbuf[256];
        struct sockaddr_in addr;

        sok = socket(AF_INET, SOCK_STREAM, 0);
        if (sok == INVALID_SOCKET) {
                free(username);
                return 0;
        }

        len = 1;
        setsockopt(sok, SOL_SOCKET, SO_REUSEADDR, (char *)&len, sizeof(len));

        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(113);

        if (bind(sok, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) {
                closesocket(sok);
                free(username);
                return 0;
        }

        if (listen(sok, 1) == SOCKET_ERROR) {
                closesocket(sok);
                free(username);
                return 0;
        }

        len = sizeof(addr);
        read_sok = accept(sok, (struct sockaddr *)&addr, &len);
        closesocket(sok);
        if (read_sok == INVALID_SOCKET) {
                free(username);
                return 0;
        }

        identd_is_running = FALSE;

        snprintf(outbuf,
                 sizeof(outbuf),
                 "%%\tServicing ident request from %s\n",
                 inet_ntoa(addr.sin_addr));
        // PrintText (current_sess, outbuf);

        recv(read_sok, buf, sizeof(buf) - 1, 0);
        buf[sizeof(buf) - 1] = 0; /* ensure null termination */

        p = strchr(buf, ',');
        if (p) {
                snprintf(outbuf,
                         sizeof(outbuf) - 1,
                         "%d, %d : USERID : UNIX : %s\r\n",
                         atoi(buf),
                         atoi(p + 1),
                         username);
                outbuf[sizeof(outbuf) - 1] = 0; /* ensure null termination */
                send(read_sok, outbuf, strlen(outbuf), 0);
        }

        sleep(1);
        closesocket(read_sok);
        free(username);

        return 0;
}
开发者ID:xchat-gnome,项目名称:xchat-gnome,代码行数:70,代码来源:identd.c

示例3: main


//.........这里部分代码省略.........
    printf("Inital pause of %d seconds\n", initial_pause);
  while (initial_pause > 0)
    initial_pause = sleep(initial_pause);
  }

/* Create sockets */

if (port == 0)  /* Unix domain */
  {
  if (debug) printf("%d: Creating Unix domain socket\n", time(NULL));
  listen_socket[udn] = socket(PF_UNIX, SOCK_STREAM, 0);
  if (listen_socket[udn] < 0)
    {
    printf("Unix domain socket creation failed: %s\n", strerror(errno));
    exit(1);
    }
  }
else
  {
  #if HAVE_IPV6
  if (use_ipv6)
    {
    if (debug) printf("Creating IPv6 socket\n");
    listen_socket[v6n] = socket(AF_INET6, SOCK_STREAM, 0);
    if (listen_socket[v6n] < 0)
      {
      printf("IPv6 socket creation failed: %s\n", strerror(errno));
      exit(1);
      }
#if defined(TCP_FASTOPEN) && !defined(__APPLE__)
    if (tfo)
      {
      int backlog = 5;
      if (setsockopt(listen_socket[v6n], IPPROTO_TCP, TCP_FASTOPEN,
                    &backlog, sizeof(backlog)))
	if (debug) printf("setsockopt TCP_FASTOPEN: %s\n", strerror(errno));
      }
#endif
    /* If this is an IPv6 wildcard socket, set IPV6_V6ONLY if that option is
    available. */

    #ifdef IPV6_V6ONLY
    if (setsockopt(listen_socket[v6n], IPPROTO_IPV6, IPV6_V6ONLY, (char *)(&on),
          sizeof(on)) < 0)
      printf("Setting IPV6_V6ONLY on IPv6 wildcard "
        "socket failed (%s): carrying on without it\n", strerror(errno));
    #endif  /* IPV6_V6ONLY */
    }
  #endif  /* HAVE_IPV6 */

  /* Create an IPv4 socket if required */

  if (use_ipv4)
    {
    if (debug) printf("Creating IPv4 socket\n");
    listen_socket[v4n] = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_socket[v4n] < 0)
      {
      printf("IPv4 socket creation failed: %s\n", strerror(errno));
      exit(1);
      }
#if defined(TCP_FASTOPEN) && !defined(__APPLE__)
    if (tfo)
      {
      int backlog = 5;
      if (setsockopt(listen_socket[v4n], IPPROTO_TCP, TCP_FASTOPEN,
开发者ID:Exim,项目名称:exim,代码行数:67,代码来源:server.c

示例4: output

/* Send the contents of the global buffer via the non-multicast socket
 */
int					/* <0 on failure */
output(enum output_type type,
       struct sockaddr_in *dst,		/* send to here */
       struct interface *ifp,
       struct rip *buf,
       int size)			/* this many bytes */
{
	struct sockaddr_in osin;
	int flags;
	const char *msg;
	int res;
	int soc;
	int serrno;

	assert(ifp != NULL);
	osin = *dst;
	if (osin.sin_port == 0)
		osin.sin_port = htons(RIP_PORT);
#ifdef _HAVE_SIN_LEN
	if (osin.sin_len == 0)
		osin.sin_len = sizeof(osin);
#endif

	soc = rip_sock;
	flags = 0;

	switch (type) {
	case OUT_QUERY:
		msg = "Answer Query";
		if (soc < 0)
			soc = ifp->int_rip_sock;
		break;
	case OUT_UNICAST:
		msg = "Send";
		if (soc < 0)
			soc = ifp->int_rip_sock;
		flags = MSG_DONTROUTE;
		break;
	case OUT_BROADCAST:
		if (ifp->int_if_flags & IFF_POINTOPOINT) {
			msg = "Send";
		} else {
			msg = "Send bcast";
		}
		flags = MSG_DONTROUTE;
		break;
	case OUT_MULTICAST:
		if ((ifp->int_if_flags & (IFF_POINTOPOINT|IFF_MULTICAST)) ==
		    IFF_POINTOPOINT) {
			msg = "Send pt-to-pt";
		} else if (ifp->int_state & IS_DUP) {
			trace_act("abort multicast output via %s"
				  " with duplicate address",
				  ifp->int_name);
			return 0;
		} else {
			msg = "Send mcast";
			if (rip_sock_mcast != ifp) {
				struct ip_mreqn mreqn;

				memset(&mreqn, 0, sizeof(struct ip_mreqn));
				mreqn.imr_ifindex = ifp->int_index;
				if (0 > setsockopt(rip_sock,
						   IPPROTO_IP,
						   IP_MULTICAST_IF,
						   &mreqn,
						   sizeof(mreqn))) {
					serrno = errno;
					LOGERR("setsockopt(rip_sock, "
					       "IP_MULTICAST_IF)");
					errno = serrno;
					ifp = NULL;
					return -1;
				}
				rip_sock_mcast = ifp;
			}
			osin.sin_addr.s_addr = htonl(INADDR_RIP_GROUP);
		}
		break;

	case NO_OUT_MULTICAST:
	case NO_OUT_RIPV2:
	default:
#ifdef DEBUG
		abort();
#endif
		return -1;
	}

	trace_rip(msg, "to", &osin, ifp, buf, size);

	res = sendto(soc, buf, size, flags,
		     (struct sockaddr *)&osin, sizeof(osin));
	if (res < 0
	    && (ifp == NULL || !(ifp->int_state & IS_BROKE))) {
		serrno = errno;
		msglog("%s sendto(%s%s%s.%d): %s", msg,
		       ifp != NULL ? ifp->int_name : "",
//.........这里部分代码省略.........
开发者ID:2trill2spill,项目名称:freebsd,代码行数:101,代码来源:output.c

示例5: void

struct DomainSocket *new_domain_socket(const char *path, int access_mask, 
    void (*read_callback)(struct DSClient *client), 
    void (*write_callback)(struct DSClient *client), 
    void (*error_callback)(struct DSClient *client),
    int listen_backlog)
{
    struct linger ling = {0, 0};
    struct sockaddr_un addr;
    struct stat tstat;
    int flags = 1;
    int old_umask;
    struct DomainSocket *uds;
    
    assert(path != NULL);
    
    uds = malloc(sizeof(struct DomainSocket));
    uds->path = strdup(path);
    uds->fd = -1;
    uds->read_callback = read_callback;
    uds->write_callback = write_callback;
    uds->error_callback = error_callback;
    
    if ((uds->fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        _DEBUG("%s: socket() failed\n", __FUNCTION__);
        free_domain_socket(uds);
        return NULL;
    }
    
    // clean up a previous socket file if we left it around
    if (lstat(path, &tstat) == 0) { 
        if (S_ISSOCK(tstat.st_mode)) {
            unlink(path);
        }
    }
    
    // @jayridge doesn't think this does anything here
    setsockopt(uds->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
    // @jayridge doesn't think this does anything here
    setsockopt(uds->fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
    setsockopt(uds->fd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
    
    // clears nonstandard fields in some impementations that otherwise mess things up
    memset(&addr, 0, sizeof(addr));
    
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
    assert(strcmp(addr.sun_path, path) == 0);
    old_umask = umask(~(access_mask & 0777));
    if (bind(uds->fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
        _DEBUG("%s: bind() failed\n", __FUNCTION__);
        free_domain_socket(uds);
        umask(old_umask);
        return NULL;
    }
    umask(old_umask);
    
    if (listen(uds->fd, listen_backlog) == -1) {
        _DEBUG("%s: listen() failed\n", __FUNCTION__);
        free_domain_socket(uds);
        return NULL;
    }
    
    if (evutil_make_socket_nonblocking(uds->fd) == -1) {
        _DEBUG("%s: evutil_make_socket_nonblocking() failed\n", __FUNCTION__);
        free_domain_socket(uds);
        return NULL;
    }
    
    event_set(&uds->ev, uds->fd, EV_READ | EV_PERSIST, accept_socket, uds);
    if (event_add(&uds->ev, NULL) == -1) {
        _DEBUG("%s: event_add() failed\n", __FUNCTION__);
        free_domain_socket(uds);
        return NULL;
    }
    
    return uds;
}
开发者ID:jayridge,项目名称:simplehttp,代码行数:77,代码来源:domain_socket.c

示例6: _aol_getclientsocket

int _aol_getclientsocket(char *host, int port)
{
    struct hostent *hp;
    int success, i, flag;
    register int s=-1;
    struct linger l;
    struct sockaddr_in sin;

    if(host==NULL || port==0)
        return(-1);

    if((hp=gethostbyname(host)) == NULL)
    {
#ifdef HAVE_HERROR
        herror("gethostbyname");
#else
        fprintf(stderr, "Error looking up %s\n", host);
#endif
        return(-1);
    }

    success=0;

    /* of course, replace that 1 with the max number of con attempts */
    for(i=0; i<1; i++)
    {
        if((s=socket(AF_INET, SOCK_STREAM, 0))<0)
        {
            perror("socket");
            return(-1);
        }

        sin.sin_family = AF_INET;
        sin.sin_port=htons(port);
        memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);

        l.l_onoff  = 1;
        l.l_linger = 60;
        setsockopt(s, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l));

        flag=1;
        if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&flag,
            sizeof(int)) <0)
        {
            puts("Nagle algorithm not dislabled.");
        }

        if(connect(s, (struct sockaddr *)&sin, sizeof(sin))<0)
        {
            sleep(1);
        }
        else
        {
            success=1;
            break;
        }
    }

    if(!success)
       s=-1;

    return(s);
}
开发者ID:WongTai,项目名称:snippets,代码行数:63,代码来源:sockets.c

示例7: socketOpenConnection


//.........这里部分代码省略.........
                    socketFree(sid);
                    return -1;
                }
            }
#endif /* (NO_GETHOSTBYNAME || VXWORKS) */
        }
    }

    bcast = sp->flags & SOCKET_BROADCAST;
    if (bcast) {
        sp->flags |= SOCKET_DATAGRAM;
    }
    dgram = sp->flags & SOCKET_DATAGRAM;

    /*
     *	Create the socket. Support for datagram sockets. Set the close on
     *	exec flag so children don't inherit the socket.
     */
    sp->sock = socket(AF_INET, dgram ? SOCK_DGRAM: SOCK_STREAM, 0);
    if (sp->sock < 0) {
        socketFree(sid);
        return -1;
    }
#ifndef __NO_FCNTL
    fcntl(sp->sock, F_SETFD, FD_CLOEXEC);
#endif
    socketHighestFd = max(socketHighestFd, sp->sock);

    /*
     *	If broadcast, we need to turn on broadcast capability.
     */
    if (bcast) {
        int broadcastFlag = 1;
        if (setsockopt(sp->sock, SOL_SOCKET, SO_BROADCAST,
                       (char *) &broadcastFlag, sizeof(broadcastFlag)) < 0) {
            socketFree(sid);
            return -1;
        }
    }

    /*
     *	Host is set if we are the client
     */
    if (host) {
        /*
         *		Connect to the remote server in blocking mode, then go into
         *		non-blocking mode if desired.
         */
        if (!dgram) {
            if (! (sp->flags & SOCKET_BLOCK)) {
                /*
                 *				sockGen.c is only used for Windows products when blocking
                 *				connects are expected.  This applies to webserver connectws.
                 *				Therefore the asynchronous connect code here is not compiled.
                 */
#if (defined (WIN) || defined (CE)) && (!defined (LITTLEFOOT) && !defined (WEBS))
                int flag;

                sp->flags |= SOCKET_ASYNC;
                /*
                 *				Set to non-blocking for an async connect
                 */
                flag = 1;
                if (ioctlsocket(sp->sock, FIONBIO, &flag) == SOCKET_ERROR) {
                    socketFree(sid);
                    return -1;
开发者ID:vladOSx,项目名称:Linux-C-Examples,代码行数:67,代码来源:sockGen.c

示例8: jk_open_socket

int jk_open_socket(struct sockaddr_in *addr, 
                   int ndelay,
                   int keepalive,
                   jk_logger_t *l)
{
    int sock;

    jk_log(l, JK_LOG_DEBUG, "Into jk_open_socket\n");

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock > -1) {
        int ret;
        /* Tries to connect to JServ (continues trying while error is EINTR) */
        do {
            jk_log(l, JK_LOG_DEBUG, "jk_open_socket, try to connect socket = %d\n", sock);
            ret = connect(sock,
                          (struct sockaddr *)addr,
                          sizeof(struct sockaddr_in));
#if defined(WIN32) || (defined(NETWARE) && defined(__NOVELL_LIBC__))
            if(SOCKET_ERROR == ret) { 
                errno = WSAGetLastError() - WSABASEERR;
            }
#endif /* WIN32 */
            jk_log(l, JK_LOG_DEBUG, "jk_open_socket, after connect ret = %d\n", ret);
        } while (-1 == ret && EINTR == errno);

        /* Check if we connected */
        if(0 == ret) {
                                                int keep = 1;
            if(ndelay) {
                int set = 1;

                jk_log(l, JK_LOG_DEBUG, "jk_open_socket, set TCP_NODELAY to on\n");
                setsockopt(sock, 
                           IPPROTO_TCP, 
                           TCP_NODELAY, 
                           (char *)&set, 
                           sizeof(set));
            }   

            if (keepalive) {
                jk_log(l, JK_LOG_DEBUG, "jk_open_socket, set SO_KEEPALIVE to on\n");
                setsockopt(sock,
                           SOL_SOCKET,
                           SO_KEEPALIVE,
                           (char *)&keep,
                           sizeof(keep));
            }

            jk_log(l, JK_LOG_DEBUG, "jk_open_socket, return, sd = %d\n", sock);
            return sock;
        }   
        jk_log(l, JK_LOG_INFO, "jk_open_socket, connect() failed errno = %d\n", errno);
        jk_close_socket(sock);
    } else {
#if defined(WIN32) || (defined(NETWARE) && defined(__NOVELL_LIBC__))
        errno = WSAGetLastError() - WSABASEERR;
#endif /* WIN32 */
        jk_log(l, JK_LOG_ERROR, "jk_open_socket, socket() failed errno = %d\n", errno);
    }    

    return -1;
}
开发者ID:devjin24,项目名称:howtomcatworks,代码行数:63,代码来源:jk_connect.c

示例9: socket

int OMXPlayerSync::setUpConnection ()
{
   int i;
   
   if ( syncType == SYNC_SERVER )
   {
      sockfd = socket(AF_INET, SOCK_STREAM, 0);
      if (-1 == sockfd) {
         perror("0:socket");
         return 1;
      }
      
      if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &forceRebind, sizeof(int))) {
         perror("0:setsockopt");
         return 1;
      }
      
      memset((void *) &server, 0, sizeof(struct sockaddr_in));
      server.sin_family = AF_INET;
      server.sin_port = htons( port );
      server.sin_addr.s_addr = INADDR_ANY;
      
      if (-1 == bind(sockfd, (const struct sockaddr *) &server,
            sizeof(struct sockaddr_in))) {
         perror("0:bind");
         return 1;
      }
      
      if (-1 == listen(sockfd, 0)) {
         perror("0:listen");
         return 1;
      }
      
      // Set up the client sockets
      for ( i = 0; i < numNodes && i < MAX_NUM_CLIENT_SOCKETS; i++)
      {
         clientSocket [ i ] = accept(sockfd, (struct sockaddr *) &client, &clientaddrlen);
         if (-1 == clientSocket [ i ]) {
            perror("0:accept");
            return 1;
         }
      }
      
      return 0;
   }
   else
   {
      sockfd = socket(AF_INET, SOCK_STREAM, 0);
      if (-1 == sockfd) {
         perror("1:socket");
         return 1;
      }
      
      if (0 != getaddrinfo(serverAddress.c_str (), NULL, NULL, &serverinfo)) {
         perror("getaddrinfo");
         return 1;
      }
      
      /*Copy size of sockaddr_in b/c res->ai_addr to big for this example*/
      memcpy(&server, serverinfo->ai_addr, sizeof(struct sockaddr_in));
      server.sin_family = AF_INET;
      server.sin_port = htons( port );
      freeaddrinfo(serverinfo);
      
#ifdef LOOP_UNTIL_CONNECT
      while ( true )
      {
         if (-1 != connect(sockfd, (const struct sockaddr *) &server,
               sizeof(struct sockaddr_in))) {
            break;
         }
         usleep ( CONNECT_SLEEP_PERIOD );
      }
#else
      if (-1 == connect(sockfd, (const struct sockaddr *) &server,
            sizeof(struct sockaddr_in))) {
         perror("1:connect");
         return 1;
      }
#endif // LOOP_UNTIL_CONNECT
      
      return 0;
   }
}
开发者ID:pukster,项目名称:omxplayer-sync-2,代码行数:84,代码来源:OMXPlayerSync.cpp

示例10: socket_server

void socket_server() {

	//The port you want the server to listen on
	int host_port= 1101;

	unsigned short wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD( 2, 2 );
 	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 ||
		    HIBYTE( wsaData.wVersion ) != 2 )) {
	    fprintf(stderr, "No sock dll %d\n",WSAGetLastError());
		goto FINISH;
	}

	//Initialize sockets and set options
	int hsock;
	int * p_int ;
	hsock = socket(AF_INET, SOCK_STREAM, 0);
	if(hsock == -1){
		printf("Error initializing socket %d\n",WSAGetLastError());
		goto FINISH;
	}
	
	p_int = (int*)malloc(sizeof(int));
	*p_int = 1;
	if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
		(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
		printf("Error setting options %d\n", WSAGetLastError());
		free(p_int);
		goto FINISH;
	}
	free(p_int);

	//Bind and listen
	struct sockaddr_in my_addr;
	my_addr.sin_family = AF_INET ;
	my_addr.sin_port = htons(host_port);
	
	memset(&(my_addr.sin_zero), 0, 8);
	my_addr.sin_addr.s_addr = INADDR_ANY ;
	
	/* if you get error in bind 
	make sure nothing else is listening on that port */
	if( bind( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
		fprintf(stderr,"Error binding to socket %d\n",WSAGetLastError());
		goto FINISH;
	}
	if(listen( hsock, 10) == -1 ){
		fprintf(stderr, "Error listening %d\n",WSAGetLastError());
		goto FINISH;
	}
	
	//Now lets do the actual server stuff

	int* csock;
	sockaddr_in sadr;
	int	addr_size = sizeof(SOCKADDR);
	
	while(true){
		printf("waiting for a connection\n");
		csock = (int*)malloc(sizeof(int));
		
		if((*csock = accept( hsock, (SOCKADDR*)&sadr, &addr_size))!= INVALID_SOCKET ){
			//printf("Received connection from %s",inet_ntoa(sadr.sin_addr));
			CreateThread(0,0,&SocketHandler, (void*)csock , 0,0);
		}
		else{
			fprintf(stderr, "Error accepting %d\n",WSAGetLastError());
		}
	}

FINISH:
;
}
开发者ID:mrkodimala,项目名称:MazeProblemThorughClientServer,代码行数:76,代码来源:WinServer.cpp

示例11: main

int main(){
	OTRL_INIT;
	OtrlUserState userstate;
	char *newmessage = NULL;
	char *nlmsg=NULL;
	OtrlMessageAppOps ui_ops;
	int sockfd, clientfd, recvbytes, recv_ret;
	socklen_t sin_size;
	char buf[1024], pwdbuf[1024];
	char *dbuf;
	struct sockaddr_in remote_addr, my_addr;
	fd_set fds;
	int one = 1;
	
	/* initialize ui callbacks */
	memset(&ui_ops, 0, sizeof(OtrlMessageAppOps));
	ui_ops.inject_message= inject_msg;
	ui_ops.gone_secure=gone_secure;
	printf("\033[31mStarting driver...\033[0m\n");

	/* initialize socket connection */
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	my_addr.sin_family=AF_INET;
	my_addr.sin_port= htons(3333);
	my_addr.sin_addr.s_addr = INADDR_ANY;
	bzero(&(my_addr.sin_zero),8);

	/* Allow rebinding to address */
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));

	if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
		perror("bind");
		exit(1);
	}
	if (listen(sockfd, 1) == -1) {
		perror("listen");
		exit(1);
	}
	sin_size = sizeof(struct sockaddr_in);
	if ((clientfd = accept(sockfd, (struct sockaddr *)&remote_addr, \
					&sin_size)) == -1) {
		perror("accept");
	}
	printf("\033[31mConnected to Bob\033[0m\n");

	/* create userstate, and read the private key */
	userstate = otrl_userstate_create();
	getcwd(pwdbuf, 1024);
	strcat(pwdbuf, "/private_key");
	otrl_privkey_read(userstate, pwdbuf);


	/* Clients send messages asynchronously*/
	while(1){
		FD_ZERO(&fds);
		FD_SET(0, &fds);
		FD_SET(clientfd, &fds);
		select(clientfd+1, &fds, NULL, NULL, NULL);
		if(FD_ISSET(0, &fds)){
			/* send message */
			fgets(buf, 1023, stdin);
			buf[strlen(buf)-1]= '\0';
			printf("\033[31mTo OTR:%d:\033[0m%s\n\033[0m",strlen(buf), buf);
			dbuf = strdup(buf);
			otrl_message_sending(userstate, &ui_ops, NULL, "[email protected]",
					"msn", "[email protected]", &dbuf, NULL, &newmessage,
					OTRL_FRAGMENT_SEND_SKIP, NULL, NULL, NULL, NULL);
			free(dbuf);
			nlmsg = (char*)malloc(strlen(newmessage)+2);			
			memcpy(nlmsg, newmessage, strlen(newmessage));
			nlmsg[strlen(newmessage)]='\n';
			nlmsg[strlen(newmessage)+1]='\0';
			send(clientfd, nlmsg, strlen(nlmsg), 0);
			printf("\033[31mTo network:%d:\033[35m%s\033[0m\n\033[0m", strlen(newmessage), newmessage);
		}else{
			/*receive message */
			recvbytes=recv(clientfd, buf, MAXDATASIZE, 0);
			if(recvbytes==0) break;
			recvbytes--;
			buf[recvbytes] = '\0';
			if(buf[recvbytes-1]=='\r'){
				 recvbytes--;
				 buf[recvbytes]='\0';
			}
			printf("\033[31mFrom network:%d:\033[35m %s\033[0m\n",recvbytes, buf);
			recv_ret=otrl_message_receiving(userstate, &ui_ops, &clientfd, "[email protected]",
					"msn", "[email protected]", buf, &newmessage, NULL,
					NULL, NULL, NULL, NULL);
			if(recv_ret==0)
				printf("\033[31mFrom OTR:%d:\033[0m %s\n", newmessage ? strlen(newmessage) : 0, newmessage);
		}
	}
	return 0;
}
开发者ID:konefes,项目名称:peed-lab3,代码行数:94,代码来源:driver.c

示例12: credis_connect

REDIS credis_connect(const char *host, int port, int timeout)
{
  int fd, rc,flags ,yes = 1, use_he = 0;
  struct sockaddr_in sa;  
  struct hostent *he;
  REDIS rhnd;

#ifdef WIN32
  unsigned long addr;
  WSADATA data;
  
  if (WSAStartup(MAKEWORD(2,2), &data) != 0) {
    DEBUG("Failed to init Windows Sockets DLL\n");
    return NULL;
  }
#endif

  if ((rhnd = cr_new()) == NULL)
    return NULL;

  if (host == NULL)
    host = "127.0.0.1";
  if (port == 0)
    port = 6379;

#ifdef WIN32
  if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ||
      setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&yes, sizeof(yes)) == -1 ||
      setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes)) == -1)
    goto error;
#else
  if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ||
      setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&yes, sizeof(yes)) == -1 ||
      setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&yes, sizeof(yes)) == -1)
    goto error;
#endif

  sa.sin_family = AF_INET;
  sa.sin_port = htons(port);

#ifdef WIN32
  /* TODO use getaddrinfo() instead! */
  addr = inet_addr(host);
  if (addr == INADDR_NONE) {
    he = gethostbyname(host);
    use_he = 1;
  }
  else {
    he = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
    use_he = 1;
  }
#else
  if (inet_aton(host, &sa.sin_addr) == 0) {
    he = gethostbyname(host);
    use_he = 1;
  }
#endif

  if (use_he) {
    if (he == NULL)
      goto error;
    memcpy(&sa.sin_addr, he->h_addr, sizeof(struct in_addr));
  } 

  /* connect with user specified timeout */

#ifndef WIN32
  flags = fcntl(fd, F_GETFL);
  if ((rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) < 0) {
    DEBUG("Setting socket non-blocking failed with: %d\n", rc);
  }
#endif

  if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
#ifndef WIN32
	  if (errno != EINPROGRESS)
      goto error;
#endif

    if (cr_selectwritable(fd, timeout) > 0) {
      int err;
      socklen_t len = sizeof(err);
      if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&err, &len) == -1 || err)
        goto error;
    }
    else /* timeout or select error */
      goto error;
  }
  /* else connect completed immediately */

  strcpy(rhnd->ip, inet_ntoa(sa.sin_addr));
  rhnd->port = port;
  rhnd->fd = fd;
  rhnd->timeout = timeout;

  /* We can receive 2 version formats: x.yz and x.y.z, where x.yz was only used prior 
   * first 1.1.0 release(?), e.g. stable releases 1.02 and 1.2.6 */
  if (cr_sendfandreceive(rhnd, CR_BULK, "INFO\r\n") == 0) {
    int items = sscanf(rhnd->reply.bulk,
                       "redis_version:%d.%d.%d\r\n",
//.........这里部分代码省略.........
开发者ID:w30afthc,项目名称:pstat,代码行数:101,代码来源:credis.cpp

示例13: dgram_ctrl


//.........这里部分代码省略.........
			switch (to->sa_family)
				{
				case AF_INET:
					memcpy(&data->peer,to,sizeof(data->peer.sa_in));
					break;
#if OPENSSL_USE_IPV6
				case AF_INET6:
					memcpy(&data->peer,to,sizeof(data->peer.sa_in6));
					break;
#endif
				default:
					memcpy(&data->peer,to,sizeof(data->peer.sa));
					break;
				}
#if 0
			}
#endif
		break;
		/* (Linux)kernel sets DF bit on outgoing IP packets */
	case BIO_CTRL_DGRAM_MTU_DISCOVER:
#ifdef OPENSSL_SYS_LINUX
		addr_len = (socklen_t)sizeof(addr);
		memset((void *)&addr, 0, sizeof(addr));
		if (getsockname(b->num, &addr.sa, &addr_len) < 0)
			{
			ret = 0;
			break;
			}
		sockopt_len = sizeof(sockopt_val);
		switch (addr.sa.sa_family)
			{
		case AF_INET:
			sockopt_val = IP_PMTUDISC_DO;
			if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
				&sockopt_val, sizeof(sockopt_val))) < 0)
				perror("setsockopt");
			break;
#if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER)
		case AF_INET6:
			sockopt_val = IPV6_PMTUDISC_DO;
			if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
				&sockopt_val, sizeof(sockopt_val))) < 0)
				perror("setsockopt");
			break;
#endif
		default:
			ret = -1;
			break;
			}
		ret = -1;
#else
		break;
#endif
	case BIO_CTRL_DGRAM_QUERY_MTU:
#ifdef OPENSSL_SYS_LINUX
		addr_len = (socklen_t)sizeof(addr);
		memset((void *)&addr, 0, sizeof(addr));
		if (getsockname(b->num, &addr.sa, &addr_len) < 0)
			{
			ret = 0;
			break;
			}
		sockopt_len = sizeof(sockopt_val);
		switch (addr.sa.sa_family)
			{
		case AF_INET:
开发者ID:10045125,项目名称:xuggle-xuggler,代码行数:67,代码来源:bss_dgram.c

示例14: dgram_adjust_rcv_timeout

static void dgram_adjust_rcv_timeout(BIO *b)
	{
#if defined(SO_RCVTIMEO)
	bio_dgram_data *data = (bio_dgram_data *)b->ptr;
	int sz = sizeof(int);

	/* Is a timer active? */
	if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0)
		{
		struct timeval timenow, timeleft;

		/* Read current socket timeout */
#ifdef OPENSSL_SYS_WINDOWS
		int timeout;
		if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
					   (void*)&timeout, &sz) < 0)
			{ perror("getsockopt"); }
		else
			{
			data->socket_timeout.tv_sec = timeout / 1000;
			data->socket_timeout.tv_usec = (timeout % 1000) * 1000;
			}
#else
		if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, 
						&(data->socket_timeout), (void *)&sz) < 0)
			{ perror("getsockopt"); }
#endif

		/* Get current time */
		get_current_time(&timenow);

		/* Calculate time left until timer expires */
		memcpy(&timeleft, &(data->next_timeout), sizeof(struct timeval));
		timeleft.tv_sec -= timenow.tv_sec;
		timeleft.tv_usec -= timenow.tv_usec;
		if (timeleft.tv_usec < 0)
			{
			timeleft.tv_sec--;
			timeleft.tv_usec += 1000000;
			}

		if (timeleft.tv_sec < 0)
			{
			timeleft.tv_sec = 0;
			timeleft.tv_usec = 1;
			}

		/* Adjust socket timeout if next handhake message timer
		 * will expire earlier.
		 */
		if ((data->socket_timeout.tv_sec == 0 && data->socket_timeout.tv_usec == 0) ||
			(data->socket_timeout.tv_sec > timeleft.tv_sec) ||
			(data->socket_timeout.tv_sec == timeleft.tv_sec &&
			 data->socket_timeout.tv_usec >= timeleft.tv_usec))
			{
#ifdef OPENSSL_SYS_WINDOWS
			timeout = timeleft.tv_sec * 1000 + timeleft.tv_usec / 1000;
			if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
						   (void*)&timeout, sizeof(timeout)) < 0)
				{ perror("setsockopt"); }
#else
			if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &timeleft,
							sizeof(struct timeval)) < 0)
				{ perror("setsockopt"); }
#endif
			}
		}
#endif
	}
开发者ID:10045125,项目名称:xuggle-xuggler,代码行数:69,代码来源:bss_dgram.c

示例15: main

int main(int ac, char **av) {

    ssize_t l;
    char buf[2000];
    int r;
    int n;

    /* Socket variables */
    int s, exp;
    u_int yes=1;
    int port;
    struct sockaddr_in me, them;
    socklen_t sl = sizeof(struct sockaddr_in);

    struct pollfd fds[2];

    /*Initialization*/{
        port=3811;
        bzero(&me,sizeof(me));
        me.sin_family= AF_INET;
        me.sin_port=htons(port);

        s=socket(AF_INET,SOCK_DGRAM,0);
        bind(s,(struct sockaddr *)&me,sizeof(me));

        exp=socket(AF_INET,SOCK_STREAM,0);
        setsockopt(exp,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes));
        bind(exp,(struct sockaddr *)&me,sizeof(me));
        listen(exp,10);

        bzero(&fds,sizeof(fds));

        fcntl(s,F_SETFL,O_NONBLOCK);
        fcntl(exp,F_SETFL,O_NONBLOCK);

        fds[0].fd = s;
        fds[0].events |= POLLIN;
        fds[1].fd = exp, fds[1].events |= POLLIN;

        db_create(&db,NULL,0);
        db->set_cachesize(db, 0, 512*1024*1024, 0);
        db->open(db,NULL,"stats.db",NULL,DB_BTREE,DB_CREATE|DB_TRUNCATE,0);

        signal(SIGHUP,hup);
        signal(SIGINT,die);
        signal(SIGTERM,die);
        signal(SIGCHLD,child);
        signal(SIGUSR1,truncatedb);
        daemon(1,0);
    }
    /* Loop! loop! loop! */
    for(;;) {
        n=0;
        r=poll(fds,2,-1);

        /* Process incoming UDP queue */
        while(( fds[0].revents & POLLIN ) &&
                ((l=recvfrom(s,&buf,1500,0,NULL,NULL))!=-1)) {
            if (l==EAGAIN)
                break;
            handleMessage((char *)&buf,l);
            n++;
            /*  Still handle export connections under high load */
            if (n==5000)
                break;
        }

        /* Process incoming TCP queue */
        while((fds[1].revents & POLLIN ) &&
                ((r=accept(exp,(struct sockaddr *)&them,&sl))!=-1)) {
            if (r==EWOULDBLOCK)
                break;
            handleConnection(r);
        }
    }
    return(0);
}
开发者ID:wikimedia,项目名称:operations-software,代码行数:77,代码来源:collector.c


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