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

C++ socket函数代码示例

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

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



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

示例1: main

int main(int argc, char *argv[])
{
  struct timespec timeBase, timeNow;
  long long delta, deltaPrevious;
  int sockfd, sockfdClient, buffLen, readLen, readIdx, count, port;
  struct sockaddr_in addrServ, addrClient;
  socklen_t addrClientLen;
  char buff[2], *buffLong, label[21];

  clock_gettime(CLOCKTYPE, &timeBase);

  port = SERVER_PORT;
  if (2 <= argc)
  {
    port = atoi(argv[1]);
    if (0 >= port)
    {
      port = SERVER_PORT;
    }
  }

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (0 > sockfd)
  {
    fprintf(stderr, "Error establishing socket.\n");
    exit(1);
  }

  bzero((char *) &addrServ, sizeof(addrServ));
  addrServ.sin_family = AF_INET;
  addrServ.sin_addr.s_addr = INADDR_ANY;
  addrServ.sin_port = htons(port);
  if (0 > bind(sockfd, (struct sockaddr *) &addrServ, sizeof(addrServ)))
  {
    fprintf(stderr, "Error binding socket to server port %d.\n", port);
    exit(1);
  }

  listen(sockfd, 5);
  printf("SERVER LISTENING ON PORT %d\n", port);
  fflush(stdout);

  // Enter loop accepting new connections
  for (count = 0;; count++)
  {
    addrClientLen = sizeof(addrClient);
    sockfdClient = accept(sockfd, (struct sockaddr *) &addrClient, &addrClientLen);
    if (0 > sockfdClient)
    {
      close(sockfd);
      fprintf(stderr, "Error accepting connection from port %d.\n", port);
      exit(1);
    }
  
    printf("NEW CONNECTION (%d)\n", count);
    fflush(stdout);
    deltaPrevious = -1;
    // Enter loop handling packets from this connection
    for (;;)
    {
      readLen = read(sockfdClient, buff, sizeof(buff));
      if (0 == readLen)
      {
        break;
      }
      if (0 > readLen)
      {
        close(sockfdClient);
        close(sockfd);
        fprintf(stderr, "Error reading from connection on port %d.\n", port);
        exit(1);
      }
#ifdef DEBUG
      printf("Read %d bytes\n", readLen);
#endif
      buffLen = (unsigned int)buff[0] + 256 * (unsigned int)buff[1];
#ifdef DEBUG
      printf("Allocating %d bytes\n", buffLen);
      fflush(stdout);
#endif
      buffLong = (char *) malloc((unsigned int)buffLen);
      if (NULL == buffLong)
      {
        close(sockfdClient);
        close(sockfd);
        fprintf(stderr, "Error allocating buffer for %d bytes.\n", buffLen);
        exit(1);
      }
      for (readIdx = 0; readIdx < buffLen; readIdx += readLen)
      {
        readLen = read(sockfdClient, buffLong + readIdx, buffLen - readIdx);
        if (0 == readLen)
        {
          break;
        } else if (0 > readLen)
        {
          close(sockfdClient);
          close(sockfd);
          fprintf(stderr, "Error reading from connection on port %d.\n", port);
          exit(1);
//.........这里部分代码省略.........
开发者ID:aesidau,项目名称:jitterclient,代码行数:101,代码来源:jitterserver.c


示例2: main

int main()
{
    int                  sock_fd, conn_fd;
    int                  optval;
    int                  flag_recv = USERNAME;
    int                  ret;
    int                  name_num;
    pid_t                pid;
    socklen_t            cli_len;
    struct sockaddr_in   cli_addr, serv_addr;
    char                 recv_buf[128];

    sock_fd = socket(AF_INET, SOCK_STREAM, 0);          //创建一个TCP套接字
    if(sock_fd < 0)
    {
        my_err("socket", __LINE__);
    }

    optval = 1;                                         //设置该套接字使之可以重新绑定端口
    if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&optval, sizeof(int)) < 0)
    {
        my_err("setsocketopt", __LINE__);
    }

    memset(&serv_addr, 0, sizeof(struct sockaddr_in));   //初始化服务器端地址结构
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERV_PORT);
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr_in)) < 0)                        //将套接字绑定到本地端口
    {
        my_err("bind", __LINE__);
    }

    if(listen(sock_fd, LISTENQ) < 0)                    //将套接字转化为监听套接字
    {
        my_err("listen", __LINE__);
    }

    cli_len = sizeof(struct sockaddr_in);
    while(1)
    {
        conn_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, &cli_len);
        if(conn_fd < 0)
        {
            my_err("accept", __LINE__);
        }

        printf("accept a new client, ip: %s\n", inet_ntoa(cli_addr.sin_addr));
        if((pid = fork()) == 0)                         //创建子进程处理刚刚接收的连接请求
        {
            while(1)                                    //子进程
            {
                if((ret = recv(conn_fd, recv_buf, sizeof(recv_buf), 0)) < 0)
                {
                    perror("recv");
                    exit(1);
                }
                recv_buf[ret - 1] = '\0';               //将数据结束标志'\n'替换成字符串结束标志

                if(flag_recv == USERNAME)               //接收到的是用户名
                {
                    name_num = find_name(recv_buf);
                    switch (name_num)
                    {
                        case -1:
                            send_data(conn_fd, "n\n");
                            break;
                        case -2:
                            exit(1);
                            break;
                        default:
                            send_data(conn_fd, "y\n");
                            flag_recv = PASSWORD;
                            break;
                    }
                }
                else if(flag_recv == PASSWORD)          //接收到的是密码 
                {
                    if (strcmp(users[name_num].password, recv_buf) == 0)
                    {
                        send_data(conn_fd, "y\n");
                        send_data(conn_fd, "welcome login my tcp server\n");
                        printf("%s login \n", users[name_num].username);
                        break;
                    }
                    else 
                    {
                        send_data(conn_fd, "n\n");
                    }
                }
            }
            close(sock_fd);
            close(sock_fd);
            exit(0);                                    //结束子进程            
        }
        else
        {
            close(conn_fd);                             //父进程关闭刚刚接收的连接请求,执行accept等待其他连接请求
        }
//.........这里部分代码省略.........
开发者ID:20032410,项目名称:linux_c,代码行数:101,代码来源:my_server.c


示例3: socket

void *threadfunction1(){

	int socketFD, sockfd2;
	int rate = DEFAULT_INTERVAL;
	char msg[141];
	double tstart, tend, ttime;
	
	struct addrinfo hints;
	struct addrinfo *servinfo;
	
	struct timespec sleepTime = {0, 100};//10000000
	
	
	//Get sockets
	socketFD = socket(AF_INET, SOCK_DGRAM, 0);
	if (socket < 0){
		printf("Error: Could not get socket.");
		exit(1);
	}
	
	//Get connection info
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE;
	
	if (getaddrinfo("10.10.66.90", "56790", &hints, &servinfo) != 0 || servinfo == NULL) {
	    printf("Error: Could not find router.");
	    exit(1);
	}


	

	int attempt = 0;
	int count = 1;
	int memory = count, temp = 0;
	int i;
	double timestamp; 
	while (numACK < NUM_PACKETS) {
        
		if (count==memory+WINDOW_SIZE || count == NUM_PACKETS) {
			count = numACK;
			memory = count;
			temp = indicator;
            
            
            tstart = (double)clock()/CLOCKS_PER_SEC;
            while (timePassed < TIME_OUT && indicator == temp) {
                tend = (double)clock()/CLOCKS_PER_SEC;

                timePassed = tend - tstart;
                //printf("%lf\n",TIME_OUT);
                //printf("Time passed : %lf\n",timePassed);
                //printf("insie while loop\n");
            }
            if (timePassed >= TIME_OUT)
            {
            	TIME_OUT *= 2;
            }
            
		}
		for (i=0; i<128; i++)
			msg[i] = '2';   // message content 
		msg[128] = '2';   // flow number
		memcpy(msg+129, &count, 4);

		timestamp = clock()/(double)CLOCKS_PER_SEC;
		memcpy(msg+133, &timestamp, 8);


		temp = indicator;
		//printf("%d\n",WINDOW_SIZE);

		if (sendto(socketFD, msg, 141, 0, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
			
			printf("Sending failed!\n");
			exit(1);
		}
        attempt += 1;
        if (attempt>=WINDOW_SIZE) {
            //printf("%f\n", (float)(numACK+(float)WINDOW_SIZE/10)/attempt);
        } else {
            //printf("%f\n", (float)(numACK)/attempt);
        }
        
		sleepTime.tv_nsec = poisson((float)R)*1000000;
		nanosleep(&sleepTime, NULL);
		count += 1;
        //printf("%d\n",numACK);
        if (numACK == NUM_PACKETS) {
            //printf("inside break\n");
            //printf("outside while\n");
            
            break;
        }
        
	}
}
开发者ID:yuchaoran2011,项目名称:EE122Sp13Proj3-ChaoranYu,代码行数:99,代码来源:client2.c


示例4: init_resolve_thread

/*
 * init_resolve_thread() starts a new thread that performs the actual
 * resolve. This function returns before the resolve is done.
 *
 * Returns FALSE in case of failure, otherwise TRUE.
 */
static bool init_resolve_thread (struct connectdata *conn,
                                 const char *hostname, int port,
                                 const Curl_addrinfo *hints)
{
  struct thread_data *td = calloc(sizeof(*td), 1);

  if (!td) {
    SetLastError(ENOMEM);
    return FALSE;
  }

  Curl_safefree(conn->async.hostname);
  conn->async.hostname = strdup(hostname);
  if (!conn->async.hostname) {
    free(td);
    SetLastError(ENOMEM);
    return FALSE;
  }

  conn->async.port = port;
  conn->async.done = FALSE;
  conn->async.status = 0;
  conn->async.dns = NULL;
  conn->async.os_specific = (void*) td;
  td->dummy_sock = CURL_SOCKET_BAD;

  /* Create the mutex used to inform the resolver thread that we're
   * still waiting, and take initial ownership.
   */
  td->mutex_waiting = CreateMutex(NULL, TRUE, NULL);
  if (td->mutex_waiting == NULL) {
    Curl_destroy_thread_data(&conn->async);
    SetLastError(EAGAIN);
    return FALSE;
  }

  /* Create the event that the thread uses to inform us that it's
   * done resolving. Do not signal it.
   */
  td->event_resolved = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (td->event_resolved == NULL) {
    Curl_destroy_thread_data(&conn->async);
    SetLastError(EAGAIN);
    return FALSE;
  }

  td->stderr_file = stderr;

#ifdef _WIN32_WCE
  td->thread_hnd = (HANDLE) CreateThread(NULL, 0,
                                         (LPTHREAD_START_ROUTINE) THREAD_FUNC,
                                         conn, 0, &td->thread_id);
#else
  td->thread_hnd = (HANDLE) _beginthreadex(NULL, 0, THREAD_FUNC,
                                           conn, 0, &td->thread_id);
#endif

#ifdef CURLRES_IPV6
  curlassert(hints);
  td->hints = *hints;
#else
  (void) hints;
#endif

  if (!td->thread_hnd) {
     SetLastError(errno);
     TRACE(("_beginthreadex() failed; %s\n", Curl_strerror(conn,errno)));
     Curl_destroy_thread_data(&conn->async);
     return FALSE;
  }
  /* This socket is only to keep Curl_resolv_fdset() and select() happy;
   * should never become signalled for read/write since it's unbound but
   * Windows needs atleast 1 socket in select().
   */
  td->dummy_sock = socket(AF_INET, SOCK_DGRAM, 0);
  return TRUE;
}
开发者ID:elambert,项目名称:honeycomb,代码行数:83,代码来源:hostthre.c


示例5: loop

void loop(void) {
    struct usb_req ureq;
    uint8_t req;
    uint16_t value, index, size;
    int yes = 1;

    uint8_t buf[255];
    int sockfd, newsockfd, portno;
    socklen_t clilen;
    struct sockaddr_in serv_addr, cli_addr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
	error("ERROR opening socket");
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = PORT;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    if (bind(sockfd, (struct sockaddr *) &serv_addr,
		sizeof(serv_addr)) < 0) 
	error("ERROR on binding");
    listen(sockfd,5);
    clilen = sizeof(cli_addr);


    for (;;) {
	newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, 
		&clilen);
	if (newsockfd < 0) 
	    error("ERROR on accept");

	while (read(newsockfd, buf, 7) == 7) {
	    req = buf[0];
	    value = buf[1] | (buf[2] << 8);
	    index = buf[3] | (buf[4] << 8);
	    size  = buf[5] | (buf[6] << 8);
	    //printf("request = 0x%x, value = 0x%x, index = 0x%x, size = 0x%x\n", req, value, index, size);
	    ureq.request = 1;
	    ureq.request = req;
	    ureq.value = value;
	    ureq.index = index;
	    ureq.length = size;

	    switch(req) {
		case 0x51:
		    //printf("read request\n");
		    if (read(newsockfd, buf, size) != size)
		    	error("read");
		    memcpy(from_client, buf, size);
		    handle_usb_vendor_int(&ureq);
		    break;
		case 0x56:
		    //printf("send request\n");
		    handle_usb_vendor_int(&ureq);
		    memcpy(buf, from_client, size);
		    if (write(newsockfd, buf, size) != size)
		    	error("write");
		    break;
		default:
		    printf("invalid request: %x\n", req);
		    exit(EXIT_FAILURE);
	    }
	}

	close(newsockfd);
    }
}
开发者ID:nieluj,项目名称:sstic2012,代码行数:70,代码来源:netserver.c


示例6: tcpserv

/**
* @brief tcpserver accept tcp connect receive data and output on debug thermal.
* @param void* parameter :unused.
*/
static void tcpserv(void* parameter)
{
   char *recv_data; /* 用于接收的指针,后面会做一次动态分配以请求可用内存 */
   u32_t sin_size;
   int sock, connected, bytes_received;
   struct sockaddr_in server_addr, client_addr;
   bool stop = FALSE; /* 停止标志 */

   recv_data = mem_malloc(RECV_BUFFER_SIZE); /* 分配接收用的数据缓冲 */
   if (recv_data == NULL)
   {
       printf("No memory\n");
       return;
   }

   /* 一个socket在使用前,需要预先创建出来,指定SOCK_STREAM为TCP的socket */
   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
   {
       /* 创建失败的错误处理 */
       printf("Socket error\n");

       /* 释放已分配的接收缓冲 */
       mem_free(recv_data);
       return;
   }

   /* 初始化服务端地址 */
   server_addr.sin_family = AF_INET;
   server_addr.sin_port = htons(TCPSERVER_PORT_NO); /* 服务端工作的端口 */
   server_addr.sin_addr.s_addr = INADDR_ANY;
   memset(&(server_addr.sin_zero),8, sizeof(server_addr.sin_zero));

   /* 绑定socket到服务端地址 */
   if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
   {
       /* 绑定失败 */
       printf("Unable to bind\n");

       /* 释放已分配的接收缓冲 */
       mem_free(recv_data);
       return;
   }

   /* 在socket上进行监听 */
   if (listen(sock, 5) == -1)
   {
       printf("Listen error\n");

       /* release recv buffer */
       mem_free(recv_data);
       return;
   }

   printf("\nTCPServer Waiting for client on port %d...\n", TCPSERVER_PORT_NO);
   while(stop != TRUE)
   {
       sin_size = sizeof(struct sockaddr_in);

       /* 接受一个客户端连接socket的请求,这个函数调用是阻塞式的 */
       connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
       /* 返回的是连接成功的socket */

       /* 接受返回的client_addr指向了客户端的地址信息 */
       printf("I got a connection from (%s , %d)\n",
                  inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

       /* 客户端连接的处理 */
       while (1)
       {
           /* 发送数据到connected socket */
           //send(connected, send_data, strlen(send_data), 0);

           /* 从connected socket中接收数据,接收buffer是1024大小,但并不一定能够收到1024大小的数据 */
           bytes_received = recv(connected,recv_data, RECV_BUFFER_SIZE, 0);
           if (bytes_received <= 0)
           {
               if(bytes_received == 0)
                   printf("client close connection.\n");
               else
                   printf("received failed, server close connection.\n");
               
               /* 接收失败,关闭这个connected socket */
               lwip_close(connected);
               break;
           }

           /* 有接收到数据,把末端清零 */
           recv_data[bytes_received] = '\0';
           if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
           {
               /* 如果是首字母是q或Q,关闭这个连接 */
               printf("receive \"q\" command, close connection.\n");
               lwip_close(connected); // close socket
               break;
           }
           else if (strcmp(recv_data, "exit") == 0)
//.........这里部分代码省略.........
开发者ID:xiaoyeqiannian,项目名称:githubck,代码行数:101,代码来源:tcpserver.c


示例7: mca_btl_tcp_endpoint_start_connect

/*
 *  Start a connection to the endpoint. This will likely not complete,
 *  as the socket is set to non-blocking, so register for event
 *  notification of connect completion. On connection we send
 *  our globally unique process identifier to the endpoint and wait for
 *  the endpoints response.
 */
static int mca_btl_tcp_endpoint_start_connect(mca_btl_base_endpoint_t* btl_endpoint)
{
    int rc,flags;
    struct sockaddr_storage endpoint_addr;
    /* By default consider a IPv4 connection */
    uint16_t af_family = AF_INET;
    opal_socklen_t addrlen = sizeof(struct sockaddr_in);
    
#if OPAL_WANT_IPV6
    if (AF_INET6 == btl_endpoint->endpoint_addr->addr_family) {
        af_family = AF_INET6;
        addrlen = sizeof (struct sockaddr_in6);
    }
#endif
    
    btl_endpoint->endpoint_sd = socket(af_family, SOCK_STREAM, 0);
    if (btl_endpoint->endpoint_sd < 0) {
        btl_endpoint->endpoint_retries++;
        return OMPI_ERR_UNREACH;
    }

    /* setup socket buffer sizes */
    mca_btl_tcp_set_socket_options(btl_endpoint->endpoint_sd);

    /* setup event callbacks */
    mca_btl_tcp_endpoint_event_init(btl_endpoint);

    /* setup the socket as non-blocking */
    if((flags = fcntl(btl_endpoint->endpoint_sd, F_GETFL, 0)) < 0) {
        BTL_ERROR(("fcntl(F_GETFL) failed: %s (%d)", 
                   strerror(opal_socket_errno), opal_socket_errno));
    } else {
        flags |= O_NONBLOCK;
        if(fcntl(btl_endpoint->endpoint_sd, F_SETFL, flags) < 0)
            BTL_ERROR(("fcntl(F_SETFL) failed: %s (%d)", 
                       strerror(opal_socket_errno), opal_socket_errno));
    }

    /* start the connect - will likely fail with EINPROGRESS */
    mca_btl_tcp_proc_tosocks(btl_endpoint->endpoint_addr, &endpoint_addr);

    opal_output_verbose(20, mca_btl_base_output, 
                        "btl: tcp: attempting to connect() to %s address %s on port %d",
                        ORTE_NAME_PRINT(&btl_endpoint->endpoint_proc->proc_ompi->proc_name),
                        opal_net_get_hostname((struct sockaddr*) &endpoint_addr),
                        ntohs(btl_endpoint->endpoint_addr->addr_port));

    if(connect(btl_endpoint->endpoint_sd, (struct sockaddr*)&endpoint_addr, addrlen) < 0) {
        /* non-blocking so wait for completion */
        if(opal_socket_errno == EINPROGRESS || opal_socket_errno == EWOULDBLOCK) {
            btl_endpoint->endpoint_state = MCA_BTL_TCP_CONNECTING;
            opal_event_add(&btl_endpoint->endpoint_send_event, 0);
            return OMPI_SUCCESS;
        }
        {
            char *address;
            address = opal_net_get_hostname((struct sockaddr*) &endpoint_addr);
            BTL_PEER_ERROR( btl_endpoint->endpoint_proc->proc_ompi,
                          ( "Unable to connect to the peer %s on port %d: %s\n",
                            address,
                           btl_endpoint->endpoint_addr->addr_port, strerror(opal_socket_errno) ) );
        }
        mca_btl_tcp_endpoint_close(btl_endpoint);
        btl_endpoint->endpoint_retries++;
        return OMPI_ERR_UNREACH;
    }

    /* send our globally unique process identifier to the endpoint */
    if((rc = mca_btl_tcp_endpoint_send_connect_ack(btl_endpoint)) == OMPI_SUCCESS) {
        btl_endpoint->endpoint_state = MCA_BTL_TCP_CONNECT_ACK;
        opal_event_add(&btl_endpoint->endpoint_recv_event, 0);
    } else {
        mca_btl_tcp_endpoint_close(btl_endpoint);
    }
    return rc;
}
开发者ID:bringhurst,项目名称:ompi,代码行数:83,代码来源:btl_tcp_endpoint.c


示例8: fopen

int Manager::Report_TCP( Target_Spec *tcp_spec )
{
	int c, scanCount, i, skfd, count = 0;
	char ifname[32];
	FILE *netInfo;
	struct ifreq ifr;

	cout << "Reporting TCP network information..." << endl;
	
	netInfo = fopen("/proc/net/dev", "r");
	assert(netInfo != NULL);
	skfd = socket(PF_INET, SOCK_DGRAM, 0);
	if (skfd < 0) {
		cerr << "Can not create socket in Manager::Report_TCP" << endl;
		return -1;
	}

	// Pull out the first two lines of the file. These two lines contain
	// labels for the columns.
	for (i = 0; i < 2; ++i) {
		do {
			c = getc(netInfo);
		} while ((c != '\n') && (c != EOF));
	}

	for (i = 0; i < MAX_NUM_INTERFACES; ++i) {
		// grab the interface names (if there are leading blanks,
		// then they are removed using the Strip() function)
		scanCount = fscanf(netInfo, "%[^:]: %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d", ifname);
		if (scanCount == EOF) {
			break;
		}
		assert(scanCount == 1);
		Strip(ifname);

		// get ip address for the interface
		strcpy(ifr.ifr_name, ifname);
		ifr.ifr_addr.sa_family = AF_INET;
		if (ioctl(skfd, SIOCGIFADDR, &ifr) == 0) {
			strncpy ( tcp_spec[count].name, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr), 
					sizeof(tcp_spec[count].name) - 1 );
			tcp_spec[count].type = TCPClientType;	// interface to access a client

			#if _DEBUG
				cout << "   Found " << tcp_spec[count].name << "." << endl;
			#endif
			count++;
		}
		else {
#if _DEBUG
			cerr << "ioctl fail in Manager::Report_TCP()" << endl;
#endif
		}
		// Skip to the next line.
		do {
			c = getc(netInfo);
		} while ((c != '\n') && (c != EOF));
	}
	fclose(netInfo);
	close(skfd);
	// All done.
	cout << "   done." << endl;
	return count;
}
开发者ID:BackupTheBerlios,项目名称:iometer-svn,代码行数:64,代码来源:IOManagerLinux.cpp


示例9: main

void main()
{
	int port = PORT;
	WSADATA wsaData;
	SOCKET sListen, sAccept;

	int iLen;  //客户地址长度
	int iSend;  //发送数据长度
	char buf[] = "hello,how are you";//需要发送的信息
	struct sockaddr_in serv, client;//服务器、客户的地址
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		printf("Winsock load failed\n");
		return;
	}

	sListen = socket(AF_INET, SOCK_STREAM, 0);//创建套接字
	if (sListen == INVALID_SOCKET)
	{
		//创建套接字失败
		printf("socket failed:%d\n", WSAGetLastError());//输出错误
		return;
	}

	//建立服务器地址
	serv.sin_family = AF_INET;
	serv.sin_port = htons(port);//把一个双字节主机字节顺序的数据转换为网络字节顺序
	serv.sin_addr.s_addr = htonl(INADDR_ANY);//把四字节主机字节顺序转换为网络字节顺序,INADDR_ANY为系统指定的IP地址

											 //绑定
	if (bind(sListen, (LPSOCKADDR)&serv, sizeof(serv)) == SOCKET_ERROR)
	{
		//绑定失败
		printf("bind() failed:%d\n", WSAGetLastError());
		return;
	}

	//进入监听状态
	if (listen(sListen, 5) == SOCKET_ERROR)//正在等待连接的最大个数是5
	{
		//侦听出错
		printf("listen() failed:%d\n", WSAGetLastError());
		return;
	}

	iLen = sizeof(client);//初始化客户地址长度

						  //进入循环等待客户端连接请求
	while (1)
	{
		sAccept = accept(sListen, (struct sockaddr*)&client, &iLen);
		if (sAccept == INVALID_SOCKET)
		{
			printf("accept() failed:%d\n", WSAGetLastError());
			break;
		}
		//printf("accepted client IP:[%s],port:[%d]\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));

		char* msg = new char[500];
		int msgLen = recv(sAccept, msg, 500, 0);
		msg[msgLen] = '\0';
		if (msgLen>0)
			printf("%s\n", msg);


		//给客户端发送数据
		iSend = send(sAccept, buf, sizeof(buf), 0);
		if (iSend == SOCKET_ERROR)
		{
			printf("send() failed:%d\n", WSAGetLastError());
			break;
		}
		else if (iSend == 0)
		{
			break;
		}
		else
		{
			printf("send() byte:%d\n", iSend);
		}

		closesocket(sAccept);
	}

	closesocket(sListen);
	WSACleanup();
}
开发者ID:leafspace,项目名称:socket-communication-system,代码行数:87,代码来源:Source.cpp


示例10: main

int main(int argc, char* argv[])
{
    WSADATA wsa; 
    SOCKET new_socket, s;
	struct sockaddr_in server, client;
    int c = sizeof(struct sockaddr_in);

	puts("TCP/IP socket ECHO v1.0 server");

	printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Initialised.\n");
     
    //Create a socket
    if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
 
    printf("Socket created.\n");
     
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8888 );
     
    //Bind
    if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
     
    puts("Bind done");

	//Listen to incoming connections
    listen(s , 3);
     
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
	while(TRUE)
	{
		new_socket = accept(s , (struct sockaddr *)&client, &c);
		if (new_socket == INVALID_SOCKET)
		{
			printf("accept failed with error code : %d" , WSAGetLastError());
		}
		else
		{
			_beginthread(sckProcessData, 0, (LPVOID)new_socket);
		}
	}

	closesocket(s);
    WSACleanup();
	return 0;
}
开发者ID:connor21,项目名称:tcpmsg-benchmark,代码行数:62,代码来源:tcpechosrv.cpp


示例11: sys_cmd_ip_info

/*
 * Returns a list of network interfaces and their ipv4 address.
 * <interface>:<address>\n
 */
int sys_cmd_ip_info(sysh_ctx_t syshc, char *value, uint16_t *out_rc, char **out_str){
    int sys_rc = MOD_OK;
    int rc = 0;
    int sock = -1;
    struct ifreq *ifreqs = NULL;
    size_t ifreqs_len = 4 * sizeof(struct ifreq);
    struct ifconf ic;
    int i;
    size_t buf_len = 1024;
    size_t buf_used = 0;

    if ( !( (*out_str) = (char*)malloc(buf_len)) ){
        if ( asprintf(out_str, "malloc: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    while ( true ){
        if ( !(ifreqs = (struct ifreq *)malloc(ifreqs_len)) ){
            sys_rc = errno;
            if ( asprintf(out_str, "malloc: %s", strerror(errno)) == -1 ){
                err("asprintf: %s\n", strerror(errno));
                *out_str = NULL;
            }
            goto done;
        }
        ic.ifc_len = ifreqs_len;
        ic.ifc_req = ifreqs;
        ioctl(sock, SIOCGIFCONF, &ic);
        if ( ic.ifc_len == ifreqs_len ) {
            free(ifreqs);
            ifreqs_len += 4 * sizeof(struct ifreq);
            continue;
        }
        break;
    }
    close(sock);
    sock = -1;

    **out_str = '\0';
    for ( i = 0; i < ic.ifc_len/sizeof(struct ifreq); i++ ) {
        if ( buf_len - buf_used - strlen(ifreqs[i].ifr_name) - 16 ) {
            if ( !((*out_str) = realloc((*out_str), buf_len + 1024)) ){
                sys_rc = errno;
                free((*out_str));
                if ( asprintf(out_str, "realloc: %s", strerror(errno)) == -1 ){
                    err("asprintf: %s\n", strerror(errno));
                    *out_str = NULL;
                }
                goto done;
            }
        }
        sprintf( (*out_str) + strlen((*out_str)), "%s:%s\n",
            ifreqs[i].ifr_name,
            inet_ntoa( ((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr ) );
        buf_used = strlen((*out_str)) + 1;
    }

done:
    if ( sock > 0 )
        close(sock);
    if ( ifreqs )
        free(ifreqs);
    (*out_rc) = (uint16_t)sys_rc;
    return rc;
}
开发者ID:jsbronder,项目名称:wrtctl,代码行数:73,代码来源:sys-cmds.c


示例12: pcap_activate_nit

static int
pcap_activate_nit(pcap_t *p)
{
	int fd;
	struct sockaddr_nit snit;

	if (p->opt.rfmon) {
		/*
		 * No monitor mode on SunOS 3.x or earlier (no
		 * Wi-Fi *devices* for the hardware that supported
		 * them!).
		 */
		return (PCAP_ERROR_RFMON_NOTSUP);
	}

	if (p->snapshot < 96)
		/*
		 * NIT requires a snapshot length of at least 96.
		 */
		p->snapshot = 96;

	memset(p, 0, sizeof(*p));
	p->fd = fd = socket(AF_NIT, SOCK_RAW, NITPROTO_RAW);
	if (fd < 0) {
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
		    "socket: %s", pcap_strerror(errno));
		goto bad;
	}
	snit.snit_family = AF_NIT;
	(void)strncpy(snit.snit_ifname, p->opt.source, NITIFSIZ);

	if (bind(fd, (struct sockaddr *)&snit, sizeof(snit))) {
		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
		    "bind: %s: %s", snit.snit_ifname, pcap_strerror(errno));
		goto bad;
	}
	if (nit_setflags(p) < 0)
		goto bad;

	/*
	 * NIT supports only ethernets.
	 */
	p->linktype = DLT_EN10MB;

	p->bufsize = BUFSPACE;
	p->buffer = (u_char *)malloc(p->bufsize);
	if (p->buffer == NULL) {
		strlcpy(p->errbuf, pcap_strerror(errno), PCAP_ERRBUF_SIZE);
		goto bad;
	}

	/*
	 * "p->fd" is a socket, so "select()" should work on it.
	 */
	p->selectable_fd = p->fd;

	/*
	 * This is (presumably) a real Ethernet capture; give it a
	 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
	 * that an application can let you choose it, in case you're
	 * capturing DOCSIS traffic that a Cisco Cable Modem
	 * Termination System is putting out onto an Ethernet (it
	 * doesn't put an Ethernet header onto the wire, it puts raw
	 * DOCSIS frames out on the wire inside the low-level
	 * Ethernet framing).
	 */
	p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
	/*
	 * If that fails, just leave the list empty.
	 */
	if (p->dlt_list != NULL) {
		p->dlt_list[0] = DLT_EN10MB;
		p->dlt_list[1] = DLT_DOCSIS;
		p->dlt_count = 2;
	}

	p->read_op = pcap_read_nit;
	p->inject_op = pcap_inject_nit;
	p->setfilter_op = install_bpf_program;	/* no kernel filtering */
	p->setdirection_op = NULL;	/* Not implemented. */
	p->set_datalink_op = NULL;	/* can't change data link type */
	p->getnonblock_op = pcap_getnonblock_fd;
	p->setnonblock_op = pcap_setnonblock_fd;
	p->stats_op = pcap_stats_nit;

	return (0);
 bad:
	pcap_cleanup_live_common(p);
	return (PCAP_ERROR);
}
开发者ID:0225kazuki,项目名称:packet_capture,代码行数:90,代码来源:pcap-nit.c


示例13: network_connect

network_connect(struct scpi_instrument *scpi)
{
	struct sockaddr_in MyAddress, MyControlAddress;
	int status;
	struct timeval timeout;
	char buf[128];

	timeout.tv_sec = SOCKETS_TIMEOUT;
	timeout.tv_usec = 0;

	/* Create socket (allocate resources) - IPv4, TCP */
	scpi->main_socket = socket(PF_INET, SOCK_STREAM, 0);

	if (scpi->main_socket == -1) {
		printf("Error: Unable to create socket (%i)...\n",errno);
		return -1;
	}

	/* set Recieve and Transmit Timeout, so connect doesn't take so long to fail */
	status = setsockopt(scpi->main_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
	if (status < 0)
		perror("setsockopt failed\n");

	status = setsockopt(scpi->main_socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,sizeof(timeout));
	if (status < 0)
		perror("setsockopt failed\n");

	/* Establish TCP connection */
	memset(&MyAddress,0,sizeof(struct sockaddr_in));
	MyAddress.sin_family = PF_INET;
	MyAddress.sin_port = htons(scpi->main_port);
	MyAddress.sin_addr.s_addr = inet_addr(scpi->ip_address);

	status = connect(scpi->main_socket, (struct sockaddr *)&MyAddress, sizeof(struct sockaddr_in));
	if(status == -1) {
		printf("Error: Unable to establish connection to ip:%s (%i)...\n",
				scpi->ip_address, errno);
		return -1;
	}

	/* Minimize latency by setting TCP_NODELAY option */
	network_setnodelay(scpi->main_socket);

	/* Ask for control port */
	sprintf(buf, "SYST:COMM:TCPIP:CONTROL?\n");
	status = send(scpi->main_socket, buf, strlen(buf), 0);
	if (status == -1)
		return -1;

	if (scpi_network_read((scpi)) == 0) {
		scpi->control_socket = scpi->main_socket;
		return 0;
	}

	sscanf(scpi->response, "%" SCNd16, &scpi->control_port);

	/* Create socket for control port */
	scpi->control_socket = socket(PF_INET, SOCK_STREAM, 0);
	if(scpi->control_socket == -1) {
		printf("Error: Unable to create control port socket (%i)...\n",errno);
		return -1;
	}

	/* Establish TCP connection to control port */
	memset(&MyControlAddress, 0, sizeof(struct sockaddr_in));
	MyControlAddress.sin_family = PF_INET;
	MyControlAddress.sin_port = htons(scpi->control_port);
	MyControlAddress.sin_addr.s_addr = inet_addr(scpi->ip_address);

	status = connect(scpi->control_socket, (struct sockaddr *) &MyControlAddress, sizeof(struct sockaddr_in));
	if(status == -1) {
		printf("Error: Unable to establish connection to control port (%i)...\n",
			errno);
		return -1;
	}

	return 0;
}
开发者ID:dirkcgrunwald,项目名称:iio-oscilloscope,代码行数:78,代码来源:scpi.c


示例14: badSource

static void badSource(char * &data)
{
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        char *replace;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        size_t dataLen = strlen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a listen socket */
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(char)] = '\0';
            /* Eliminate CRLF */
            replace = strchr(data, '\r');
            if (replace)
            {
                *replace = '\0';
            }
            replace = strchr(data, '\n');
            if (replace)
            {
                *replace = '\0';
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
}
开发者ID:maurer,项目名称:tiamat,代码行数:82,代码来源:CWE134_Uncontrolled_Format_String__char_listen_socket_fprintf_43.cpp


示例15: start_net

//  Create socket, make non-blocking
S32 start_net(S32& socket_out, int& nPort)
{
	int hSocket, nRet;
	int snd_size = SEND_BUFFER_SIZE;
	int rec_size = RECEIVE_BUFFER_SIZE;

	socklen_t buff_size = 4;
    
	//  Create socket
    hSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (hSocket < 0)
	{
		llwarns << "socket() failed" << llendl;
		return 1;
	}

	// Don't bind() if we want the operating system to assign our ports for 
	// us.
	if (NET_USE_OS_ASSIGNED_PORT == nPort)
	{
		// Do nothing; the operating system will do it for us.
	}
	else
	{
	    // Name the socket (assign the local port number to receive on)
		stLclAddr.sin_family      = AF_INET;
		stLclAddr.sin_addr.s_addr = htonl(INADDR_ANY);
		stLclAddr.sin_port        = htons(nPort);
		U32 attempt_port = nPort;
		llinfos << "attempting to connect on port " << attempt_port << llendl;

		nRet = bind(hSocket, (struct sockaddr*) &stLclAddr, sizeof(stLclAddr));
		if (nRet < 0)
		{
			// If we got an address in use error...
			if (errno == EADDRINUSE)
			{
				// Try all ports from PORT_DISCOVERY_RANGE_MIN to PORT_DISCOVERY_RANGE_MAX
				for(attempt_port = PORT_DISCOVERY_RANGE_MIN;
					attempt_port <= PORT_DISCOVERY_RANGE_MAX;
					attempt_port++)
				{
					stLclAddr.sin_port = htons(attempt_port);
					llinfos << "trying port " << attempt_port << llendl;
					nRet = bind(hSocket, (struct sockaddr*) &stLclAddr, sizeof(stLclAddr));
					if (!((nRet < 0) && (errno == EADDRINUSE)))
					{
						break;
					}
				}
				if (nRet < 0)
				{
					llwarns << "startNet() : Couldn't find available network port." << llendl;
					// Fail gracefully in release.
					return 3;
				}
			}
			// Some other socket error
			else
			{
				llwarns << llformat ("bind() port: %d failed, Err: %s\n", nPort, strerror(errno)) << llendl;
				// Fail gracefully in release.
				return 4;
			}
		}
		llinfos << "connected on port " << attempt_port << llendl;
		nPort = attempt_port;
	}
	// Set socket to be non-blocking
 	fcntl(hSocket, F_SETFL, O_NONBLOCK);
	// set a large receive buffer
	nRet = setsockopt(hSocket, SOL_SOCKET, SO_RCVBUF, (char *)&rec_size, buff_size);
	if (nRet)
	{
		llinfos << "Can't set receive size!" << llendl;
	}
	nRet = setsockopt(hSocket, SOL_SOCKET, SO_SNDBUF, (char *)&snd_size, buff_size);
	if (nRet)
	{
		llinfos << "Can't set send size!" << llendl;
	}
	getsockopt(hSocket, SOL_SOCKET, SO_RCVBUF, (char *)&rec_size, &buff_size);
	getsockopt(hSocket, SOL_SOCKET, SO_SNDBUF, (char *)&snd_size, &buff_size);

	llinfos << "startNet - receive buffer size : " << rec_size << llendl;
	llinfos << "startNet - send buffer size    : " << snd_size << llendl;

	//  Setup a destination address
	char achMCAddr[MAXADDRSTR] = "127.0.0.1";	/* Flawfinder: ignore */ 
	stDstAddr.sin_family =      AF_INET;
        stDstAddr.sin_addr.s_addr = inet_addr(achMCAddr);
        stDstAddr.sin_port =        htons(nPort);

	socket_out = hSocket;
	return 0;
}
开发者ID:AlexRa,项目名称:Kirstens-clone,代码行数:97,代码来源:net.cpp


示例16: bad

void bad()
{
    wchar_t * data;
    wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        wchar_t *replace;
        SOCKET connectSocket = INVALID_SOCKET;
        size_t dataLen = wcslen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            /* Abort on error or the connection was closed */
            recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
            /* Eliminate CRLF */
            replace = wcschr(data, L'\r');
            if (replace)
            {
                *replace = L'\0';
            }
            replace = wcschr(data, L'\n');
            if (replace)
            {
                *replace = L'\0';
            }
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    badSink(&data);
}
开发者ID:maurer,

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ socketClose函数代码示例发布时间:2022-05-30
下一篇:
C++ sockerror函数代码示例发布时间: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