• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ setsockopt函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: sio_open

int sio_open(int &argc, char ** &argv, const char*g_appname, const char*ver, const char*client) {
  
  char * port_str = getenv("SODACTRL_PORT");
  if (port_str) {
	// connect socket
	int port = atoi(port_str);
	if (port <= 0) {
	  fprintf(stderr, "Invalid port number (SODACTRL_PORT): %s\n", port_str);
	  return -1;
	};
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd < 0) {
	  perror("Cannot create socket"); return -1;
	};
	struct linger ling;
	ling.l_onoff = 1;
	ling.l_linger = 10; // try to send data for up to 10 seconds...
	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) {
	  perror("setsockopt(linger) failed");
	};

	struct sockaddr_in servaddr;
	struct hostent *host;
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	const char * ip =  getenv("SODACTRL_IP");
	if (!ip) ip = "127.0.0.1";
	servaddr.sin_addr.s_addr =inet_addr(ip);

	if (connect(fd, (sockaddr*)&servaddr, sizeof(servaddr)) < 0){
	  char bf[512];
	  snprintf(bf, sizeof(bf), "Cannot connect to %s:%d", ip, port);
	  perror(bf);
	  return -1;
	}
	ser_fd_read = ser_fd_write = fd;

  } else {
	// use STDIN/STDOUT
	ser_fd_read = 0;
	ser_fd_write = 1;
  };

  fcntl(ser_fd_read, F_SETFL, O_NONBLOCK);
  fcntl(ser_fd_write, F_SETFL, O_NONBLOCK);
  
  char * dbgc = getenv("SERVIO_DEBUG");
  sio_dbglevel = dbgc ? atoi(dbgc) : 50;

  char * commd = getenv("SERVIO_COMMDUMP");
  sio_commdump = commd ? atoi(commd) : 0;

  const char* proto = "106";

  if (g_appname[0] == '+') {
	proto = "101";
	g_appname++;
  };

  appname = strdup(g_appname);
  if (sio_write(SIO_DATA, "SYS-INIT\t%s\t%s\t%s\t%d\t%s",
				proto, appname, ver, getpid(), (client?client:"")) == -1) {
	perror("Cannot write to server");
	return -1;
  };

  
  noserv_mode = 0; 
  // no need for 'SYS_WELCOME' when debug env is set - thus can run from console easliy
  if (isatty(ser_fd_read) && (ser_fd_read != ser_fd_write)) {
	noserv_mode = 1;
	printf("Using NO-SERVER mode - taking data, commands from tty, disabling GET\n");
	return 0;
  };

  // the only possible response to SYS-INIT with version 101 is SYS-WELCOME
  // wait 10 seconds for it...
  std::string resp;
  if (sio_read(resp, 10*1000) <= 0)  { 
	fprintf(stderr, "Server initial response timed out\n");
	return -1; // no reponse
  };
  if (resp.substr(0, 12)!="SYS-WELCOME\t") {
	for (int i=0; i<resp.length(); i++) 
	  if (resp[i]<32) resp[i]='#';
	fprintf(stderr, "Server initial response is junk: %s\n", resp.c_str());
	return -1;
  };
  return 0;
};
开发者ID:chezbob,项目名称:chezbob,代码行数:91,代码来源:servio.cpp


示例17: main

int main(int argc, char *argv[])
{
	int connSock;
	int in;
	int i;
	int ret;
	int flags;
	struct sockaddr_in servaddr;
	struct sctp_status status;
	struct sctp_sndrcvinfo sndrcvinfo;
	struct sctp_event_subscribe events;
	struct sctp_initmsg initmsg;
	char buffer[MAX_BUFFER + 1];
	char inBuffer[MAX_BUFFER + 1];

	/* Create an SCTP TCP-Style Socket */
	connSock = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);

	/* Specify that a maximum of 5 streams will be available per socket */
	memset(&initmsg, 0, sizeof(initmsg));
	initmsg.sinit_num_ostreams = 5;
	initmsg.sinit_max_instreams = 5;
	initmsg.sinit_max_attempts = 4;
	ret = setsockopt(connSock, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(initmsg));

	/* Specify the peer endpoint to which we'll connect */
	bzero((void *) &servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(MY_PORT_NUM);
	servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

	/* Connect to the server */
	ret = connect(connSock, (struct sockaddr *) &servaddr, sizeof(servaddr));

	/* Enable receipt of SCTP Snd/Rcv Data via sctp_recvmsg */
	memset((void *) &events, 0, sizeof(events));
	events.sctp_data_io_event = 1;
	ret = setsockopt(connSock, SOL_SCTP, SCTP_EVENTS, (const void *) &events, sizeof(events));

	/* Read and emit the status of the Socket (optional step) */
	in = sizeof(status);
	ret = getsockopt(connSock, SOL_SCTP, SCTP_STATUS, (void *) &status, (socklen_t *) &in);

	printf("assoc id = %d\n", status.sstat_assoc_id);
	printf("state = %d\n", status.sstat_state);
	printf("instrms = %d\n", status.sstat_instrms);
	printf("outstrms = %d\n", status.sstat_outstrms);

	/* Expect two messages from the peer */
	for (i = 0 ; i < 2 ; i++) {
		in = sctp_recvmsg(connSock, (void *) buffer, sizeof(buffer), (struct sockaddr *) NULL, 0, &sndrcvinfo, &flags);

		if (in > 0) {
			//buffer[in] = 0;
			strncpy(inBuffer, buffer, in);

			if (sndrcvinfo.sinfo_stream == LOCALTIME_STREAM) {
				printf("(Local) %s", buffer);
			}
			else if (sndrcvinfo.sinfo_stream == GMT_STREAM) {
				printf("(GMT) %s", buffer);
			}
		}
	}

	/* Close our socket and exit */
	close(connSock);

	return 0;
}
开发者ID:d1v0id,项目名称:UniversityProjects,代码行数:70,代码来源:sctp_time_client.c


示例18: get_boundsock

/* returns a bound socket matching a connection request *
 * sets verdict on request packet if ipq or nfq was used and the port is already bound *
 * in the latter case, -1 is returned */
int get_boundsock(struct sockaddr_in *server_addr, uint16_t port, int type) {
    int fd, sockopt;
#ifdef USE_IPQ_MON
    int status;
#endif

    if ((type != SOCK_DGRAM) && (type != SOCK_STREAM)) {
        logmsg(LOG_ERR, 1, "Error - Socket type %d not supported.\n", type);
        exit(EXIT_FAILURE);
    }

    if (!(fd = socket(AF_INET, type, 0))) {
        logmsg(LOG_ERR, 1, "Error - Could not create socket: %m.\n");
        exit(EXIT_FAILURE);
    }

    sockopt = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) < 0)
        logmsg(LOG_WARN, 1, "Warning - Unable to set SO_R 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ setstack_l1_B函数代码示例发布时间:2022-05-30
下一篇:
C++ setreuid函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap