Example #1
0
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);
        }
      }
      if (0 == readLen)
      {
        break;
      }
      if (readIdx > sizeof(label) - 1)
      {
        readIdx = sizeof(label) - 1;
      }
      strncpy(label, buffLong, readIdx);
      label[readIdx] = 0;
      clock_gettime(CLOCKTYPE, &timeNow);
      delta = timespecDiff(&timeNow, &timeBase);
      if (-1 == deltaPrevious)
      {
        printf(":%d:%ld::%s:\n", count, (long)(delta / 1000000), label);
      } else
      {
        printf(":%d:%ld:%ld:%s:\n", count, (long)(delta / 1000000), (long)((delta - deltaPrevious) / 1000000), label);
      }
      fflush(stdout);
      deltaPrevious = delta;
      free(buffLong);
    }
  
    close(sockfdClient);
    printf("CONNECTION CLOSED (%d)\n", count);
    fflush(stdout);
  }
  close(sockfd);

  return 0;
}
Example #2
0
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等待其他连接请求
        }
    }
    return 0;
}
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;
        }
        
	}
}
Example #4
0
/*
 * 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;
}
Example #5
0
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);
    }
}
Example #6
0
/**
* @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)
           {
               /* 如果接收的是exit,则关闭整个服务端 */
               printf("receive \"exit\" command, exit tcpserver task.\n");
               lwip_close(connected); // close socket
               stop = TRUE;
               break;
           }
           else
           {
               /* 在控制终端显示收到的数据 */
               printf("RECIEVED DATA = %s \n" , recv_data);
           }
       } // end of while(1)
   } // end of while(stop != TRUE)

   /* 释放接收缓冲 */
   mem_free(recv_data);

   return ;
}
Example #7
0
/*
 *  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;
}
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;
}
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();
}
Example #10
0
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;
}
Example #11
0
/*
 * 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;
}
Example #12
0
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);
}
Example #13
0
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;
}
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
    }
}
Example #15
0
//  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;
}
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);
}
void CWE197_Numeric_Truncation_Error__int_listen_socket_to_char_07_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    if(staticFive==5)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            char inputBuffer[CHAR_ARRAY_SIZE];
            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, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */
        char charData = (char)data;
        printHexCharLine(charData);
    }
}
Example #18
0
int main(int argc, char const *argv[]) {
  int sockfd, status;
  struct addrinfo hints, *serverinfo, *p;
  struct sockaddr_storage their_addr;
  int rv, j;
  int numbytes;
  char buf[MAXBUFLEN];
  socklen_t addr_len;
  struct timeval tv;
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  if(atoi(argv[1]) == 2) {
  sleep(5);

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_DGRAM;
  hints.ai_flags = AI_PASSIVE;

  if((rv = getaddrinfo(NULL, COM_PORT, &hints, &serverinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }

  for(p = serverinfo; p !=NULL; p->ai_next) {
    if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
      perror("listener:socket");
      continue;
    }

setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

    if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      perror("listener:bind");
      continue;
    }
    break;
  }

  if (p == NULL) {
    fprintf(stderr, "listener:failed to bind to socket\n");
  }

  freeaddrinfo(serverinfo);



  while(1) {


    addr_len = sizeof their_addr;

    if((numbytes = recvfrom(sockfd,buf, MAXBUFLEN-1, 0,(struct sockaddr*)&their_addr, &addr_len)) == -1 ) {
      perror("recvfrom");
      printf("Timeout of process one\n");

      close(sockfd);

      memset(&hints, 0, sizeof hints);
      hints.ai_family = AF_UNSPEC;
      hints.ai_socktype = SOCK_DGRAM;

      if((rv = getaddrinfo("127.0.0.1", COM_PORT, &hints, &serverinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
      }

      for(p = serverinfo; p != NULL; p = p->ai_next) {
        if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
          perror("talker:socket");
          continue;
        }
        break;
      }

      if(p == NULL) {
        fprintf(stderr, "talker: failed to create socket");
        return 2;
      }

      status = system("gnome-terminal -x bash -c './process_pairs 2'");

      while(1) {
        printf("process one:%d\n",j);

        sprintf(buf, "%d", j);

        if((numbytes = sendto(sockfd, buf , strlen(buf), 0, p->ai_addr, p->ai_addrlen)) == -1) {
          perror("talker: sendto");
          exit(1);
        }

        j++;
        if(j > 4) {
          j = 1;
        }
        sleep(1);
      }

    }


    j = atoi(buf);
    printf("process two:%d\n",j);
    sleep(1);


}

  printf( "%s\n",buf);
  close(sockfd);


} else if(atoi(argv[1]) == 1) {

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_DGRAM;

  if((rv = getaddrinfo("127.0.0.1", COM_PORT, &hints, &serverinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }

  for(p = serverinfo; p != NULL; p = p->ai_next) {
    if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
      perror("talker:socket");
      continue;
    }
    break;
  }

  if(p == NULL) {
    fprintf(stderr, "talker: failed to create socket");
    return 2;
  }
  j = 1;


  status = system("gnome-terminal -x bash -c './process_pairs 2'");

  while(1) {

  sprintf(buf, "%d", j);
  if((numbytes = sendto(sockfd, buf , strlen(buf), 0, p->ai_addr, p->ai_addrlen)) == -1) {
    perror("talker: sendto");
    exit(1);
  }

  printf("%d\n",j);
  j++;

  if(j > 4)
  {
    j = 1;
  }

  sleep(1);
  }

  freeaddrinfo(serverinfo);

  close(sockfd);


}


}
Example #19
0
/**
 * \brief Main application function.
 *
 * Application entry point.
 * Initialize board and WINC1500 Wi-Fi module.
 * Read input data from serial interface and sent it to the remote device.
 *
 * \return program return value.
 */
int main(void)
{
	tstrWifiInitParam param;
	int8_t ret;

	/* Initialize the board. */
	system_init();

	/* Initialize the UART console. */
	configure_console();
	printf(STRING_HEADER);

	/* Initialize the BSP. */
	nm_bsp_init();

	/* Initialize Wi-Fi parameters structure. */
	memset((uint8_t *)&param, 0, sizeof(tstrWifiInitParam));

	/* Initialize Wi-Fi driver with data and status callbacks. */
	param.pfAppWifiCb = wifi_cb;
	ret = m2m_wifi_init(&param);
	if (M2M_SUCCESS != ret) {
		printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
		while (1) {
		}
	}

	/* Initialize socket interface. */
	socketInit();
	registerSocketCallback(socket_cb, NULL);

	/* Connect to router. */
	m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID),
			MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL);

	while (1) {
		if (wifi_connected == M2M_WIFI_CONNECTED && tcp_server_socket < 0) {
			struct sockaddr_in addr;

			/* Create TCP server socket. */
			if ((tcp_server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
				printf("Failed to create TCP server socket!\r\n");
				continue;
			}

			/* Initialize socket address structure and bind service. */
			addr.sin_family = AF_INET;
			addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT);
			addr.sin_addr.s_addr = 0;
			bind(tcp_server_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
		}

		/* Handle pending events from network controller. */
		m2m_wifi_handle_events(NULL);

		/* Try to read user input from EDBG. */
		usart_read_job(&cdc_uart_module, &uart_ch_buffer);

		/* Handle user message from EDBG. */
		handle_input_message();
	}

	return 0;
}
Example #20
0
int main(void){
    
    int server_Socket, accept_Socket;
    unsigned int length, count;
    struct sockaddr_in server_Struct, client_Struct;
    char got_charachter[1000];
    char web_Site[]="HTTP/1.1 200 OK\r\n\r\n";
    unsigned short int port_No=5000;
    char *position_of_GET,*position_of_HTTP;
    char nameof_File[100];
    
    server_Socket=socket(AF_INET,SOCK_STREAM,0);
    
    
    server_Struct.sin_family=AF_INET;
    server_Struct.sin_addr.s_addr=htonl(INADDR_ANY);
    server_Struct.sin_port=htons(port_No);
    length=sizeof(server_Struct);
   
    
    printf("\n Server is now binding....");
    bind(server_Socket,(struct sockaddr *)&server_Struct,length);
   
    printf("\n Server listen....");
    //printf("\n Server mit IP %s on port %d ",ip_Adress,port_No);
    listen(server_Socket,5);
    
    while(1){
        
        printf("\n Server accept.....");
        fflush(stdout);
        accept_Socket=accept(server_Socket,(struct sockaddr *)&client_Struct, &length);
      
        printf(" connected to %s",inet_ntoa(client_Struct.sin_addr));
        
        count=read(accept_Socket,got_charachter,sizeof(got_charachter));
        got_charachter[count]=0;
        printf("server got the charachters %s",got_charachter);
        
        
       if(position_of_GET=strstr(got_charachter,"GET"))
       {
         printf("\n GET command start at char %ld\n\n",(position_of_GET-got_charachter)+1);
              if(position_of_HTTP=strstr(got_charachter,"HTTP"))
              {
                printf("\n GET command start at char %ld\n\n",(position_of_HTTP-got_charachter)+1);
                length=position_of_HTTP-position_of_GET-6;
                strncpy(nameof_File,position_of_GET+4,length+1);
                nameof_File[length+1]=0;
                printf("\n The name of File you asked for %s is not available at this moment",nameof_File);
              }
                else
              {
                      printf("\n HTTP has no HTTP \n\n");
              }
       }
       else
       {
           printf("\n HTTP has no GET \n\n");
       }
       
       printf("\n\n\n");
        write(accept_Socket,web_Site,sizeof(web_Site));
        printf("\n\n server close()....");
        close(accept_Socket);
    
        
        
        
    }

    
    
    
    
    return (0);
}
Example #21
0
void run(EpmdVars *g)
{
  int listensock;
  int i;
  int opt;
  struct EPMD_SOCKADDR_IN iserv_addr;

  node_init(g);
  g->conn = conn_init(g);

  dbg_printf(g,2,"try to initiate listening port %d", g->port);
  
  if ((listensock = socket(FAMILY,SOCK_STREAM,0)) < 0) {
    dbg_perror(g,"error opening stream socket");
    epmd_cleanup_exit(g,1);
  }
  g->listenfd = listensock;

  /*
   * Initialize number of active file descriptors.
   * Stdin, stdout, and stderr are still open.
   * One for the listen socket.
   */
  g->active_conn = 3+1;
  
  /*
   * Note that we must not enable the SO_REUSEADDR on Windows,
   * because addresses will be reused even if they are still in use.
   */
  
#if (!defined(__WIN32__) && !defined(_OSE_))
  /* We ignore the SIGPIPE signal that is raised when we call write
     twice on a socket closed by the other end. */
  signal(SIGPIPE, SIG_IGN);

  opt = 1;			/* Set this option */
  if (setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR,(char* ) &opt,
		 sizeof(opt)) <0) {
    dbg_perror(g,"can't set sockopt");
    epmd_cleanup_exit(g,1);
  }
#endif
  
  /* In rare cases select returns because there is someone
     to accept but the request is withdrawn before the
     accept function is called. We set the listen socket
     to be non blocking to prevent us from being hanging
     in accept() waiting for the next request. */
#ifdef _OSE_  
  opt = 1;
  if (ioctl(listensock, FIONBIO, (char*)&opt) != 0)
#else
#if (defined(__WIN32__) || defined(NO_FCNTL))
  opt = 1;
  if (ioctl(listensock, FIONBIO, &opt) != 0) /* Gives warning in VxWorks */
#else
  opt = fcntl(listensock, F_GETFL, 0);
  if (fcntl(listensock, F_SETFL, opt | O_NONBLOCK) == -1)
#endif /* __WIN32__ || VXWORKS */
#endif /* _OSE_ */
    dbg_perror(g,"failed to set non-blocking mode of listening socket %d",
	       listensock);

  { /* store port number in unsigned short */
    unsigned short sport = g->port;
    SET_ADDR_ANY(iserv_addr, FAMILY, sport);
  }
  
#ifdef _OSE_
  {
    int optlen = sizeof(opt);
    opt = 1;
    if(getsockopt(listensock, SOL_SOCKET, SO_REUSEADDR,
		  (void*)&opt, &optlen) < 0)
      fprintf(stderr, "\n\nGETSOCKOPT FAILS! %d\n\n", errno);
    else if(opt == 1)
      fprintf(stderr, "SO_REUSEADDR is set!\n");
  }
#endif

  if(bind(listensock,(struct sockaddr*) &iserv_addr, sizeof(iserv_addr)) < 0 )
    {
      if (errno == EADDRINUSE)
	{
	  dbg_tty_printf(g,1,"there is already a epmd running at port %d",
			 g->port);
	  epmd_cleanup_exit(g,0);
	}
      else
	{
	  dbg_perror(g,"failed to bind socket");
	  epmd_cleanup_exit(g,1);
	}
    }

  dbg_printf(g,2,"starting");

  listen(listensock, SOMAXCONN);


  FD_ZERO(&g->orig_read_mask);
  FD_SET(listensock,&g->orig_read_mask);

  dbg_tty_printf(g,2,"entering the main select() loop");

 select_again:
  while(1)
    {	
      fd_set read_mask = g->orig_read_mask;
      struct timeval timeout;
      int ret;

      /* If we are idle we time out now and then to enable the code
	 below to close connections that are old and probably
	 hanging. Make sure that select will return often enough. */

      timeout.tv_sec = (g->packet_timeout < IDLE_TIMEOUT) ? 1 : IDLE_TIMEOUT;
      timeout.tv_usec = 0;

      if ((ret = select(g->max_conn,&read_mask,(fd_set *)0,(fd_set *)0,&timeout)) < 0)
	dbg_perror(g,"error in select ");
      else {
	time_t now;
	if (ret == 0) {
	  FD_ZERO(&read_mask);
	}
	if (g->delay_accept) {		/* Test of busy server */
	  sleep(g->delay_accept);
	}

	if (FD_ISSET(listensock,&read_mask)) {
	  if (do_accept(g, listensock) && g->active_conn < g->max_conn) {
	    /*
	     * The accept() succeeded, and we have at least one file
	     * descriptor still free, which means that another accept()
	     * could succeed. Go do do another select(), in case there
	     * are more incoming connections waiting to be accepted.
	     */
	    goto select_again;
	  }
	}
	  
	/* Check all open streams marked by select for data or a
	   close.  We also close all open sockets except ALIVE
	   with no activity for a long period */

	now = current_time(g);
	for (i = 0; i < g->max_conn; i++) {
	  if (g->conn[i].open == EPMD_TRUE) {
	    if (FD_ISSET(g->conn[i].fd,&read_mask))
	      do_read(g,&g->conn[i]);
	    else if ((g->conn[i].keep == EPMD_FALSE) &&
		     ((g->conn[i].mod_time + g->packet_timeout) < now)) {
	      dbg_tty_printf(g,1,"closing because timed out on receive");
	      epmd_conn_close(g,&g->conn[i]);
	    }
	  }
	}
      }
    }
}
Example #22
0
/*
 * Curl_getaddrinfo() when built ipv6-enabled (non-threading and
 * non-ares version).
 *
 * Returns name information about the given hostname and port number. If
 * successful, the 'addrinfo' is returned and the forth argument will point to
 * memory we need to free after use. That memory *MUST* be freed with
 * Curl_freeaddrinfo(), nothing else.
 */
Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
                                const char *hostname,
                                int port,
                                int *waitp)
{
  struct addrinfo hints;
  Curl_addrinfo *res;
  int error;
  char sbuf[NI_MAXSERV];
  char *sbufptr = NULL;
  char addrbuf[128];
  int pf;
  struct SessionHandle *data = conn->data;

  *waitp = 0; /* synchronous response only */

  /*
   * Check if a limited name resolve has been requested.
   */
  switch(data->set.ip_version) {
  case CURL_IPRESOLVE_V4:
    pf = PF_INET;
    break;
  case CURL_IPRESOLVE_V6:
    pf = PF_INET6;
    break;
  default:
    pf = PF_UNSPEC;
    break;
  }

  if (pf != PF_INET) {
    /* see if we have an IPv6 stack */
    curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0);
    if(s == CURL_SOCKET_BAD) {
      /* Some non-IPv6 stacks have been found to make very slow name resolves
       * when PF_UNSPEC is used, so thus we switch to a mere PF_INET lookup if
       * the stack seems to be a non-ipv6 one. */

      pf = PF_INET;
    }
    else {
      /* This seems to be an IPv6-capable stack, use PF_UNSPEC for the widest
       * possible checks. And close the socket again.
       */
      sclose(s);
    }
  }

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = pf;
  hints.ai_socktype = conn->socktype;

  if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) ||
     (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) {
    /* the given address is numerical only, prevent a reverse lookup */
    hints.ai_flags = AI_NUMERICHOST;
  }
#ifdef HAVE_GSSAPI
  if(conn->data->set.krb)
    /* if krb is used, we (might) need the canonical host name */
    hints.ai_flags |= AI_CANONNAME;
#endif

  if(port) {
    snprintf(sbuf, sizeof(sbuf), "%d", port);
    sbufptr=sbuf;
  }
  error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res);
  if(error) {
    infof(data, "getaddrinfo(3) failed for %s:%d\n", hostname, port);
    return NULL;
  }

  dump_addrinfo(conn, res);

  return res;
}
Example #23
0
/*
 * Curl_getaddrinfo() - for Windows threading IPv6 enabled
 */
Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
                                char *hostname,
                                int port,
                                int *waitp)
{
  struct addrinfo hints, *res;
  int error;
  char sbuf[NI_MAXSERV];
  curl_socket_t s;
  int pf;
  struct SessionHandle *data = conn->data;

  *waitp = FALSE; /* default to synch response */

  /* see if we have an IPv6 stack */
  s = socket(PF_INET6, SOCK_DGRAM, 0);
  if (s == CURL_SOCKET_BAD) {
    /* Some non-IPv6 stacks have been found to make very slow name resolves
     * when PF_UNSPEC is used, so thus we switch to a mere PF_INET lookup if
     * the stack seems to be a non-ipv6 one. */

    pf = PF_INET;
  }
  else {
    /* This seems to be an IPv6-capable stack, use PF_UNSPEC for the widest
     * possible checks. And close the socket again.
     */
    sclose(s);

    /*
     * Check if a more limited name resolve has been requested.
     */
    switch(data->set.ip_version) {
    case CURL_IPRESOLVE_V4:
      pf = PF_INET;
      break;
    case CURL_IPRESOLVE_V6:
      pf = PF_INET6;
      break;
    default:
      pf = PF_UNSPEC;
      break;
    }
  }

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = pf;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_CANONNAME;
  itoa(port, sbuf, 10);

  /* fire up a new resolver thread! */
  if (init_resolve_thread(conn, hostname, port, &hints)) {
    *waitp = TRUE;  /* please wait for the response */
    return NULL;
  }

  /* fall-back to blocking version */
  infof(data, "init_resolve_thread() failed for %s; %s\n",
        hostname, Curl_strerror(conn,GetLastError()));

  error = getaddrinfo(hostname, sbuf, &hints, &res);
  if (error) {
    infof(data, "getaddrinfo() failed for %s:%d; %s\n",
          hostname, port, Curl_strerror(conn,WSAGetLastError()));
    return NULL;
  }
  return res;
}
Example #24
0
int main()
{
    int sock, listener;
    struct sockaddr_in addr;
    char buf[1024];
    int bytes_read;

    listener = socket(AF_INET, SOCK_STREAM, 0);
    if(listener < 0)
    {
        perror("socket");
        exit(1);
    }
    
    addr.sin_family = AF_INET;
    addr.sin_port = htons(3425);
    addr.sin_addr.s_addr = INADDR_ANY;
    if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("bind");
        exit(2);
    }

    listen(listener, 1);
    
    while(1)
    {
        sock = accept(listener, NULL, NULL);
        if(sock < 0)
        {
            perror("accept");
            exit(3);
        }
        
        switch(fork())
        {
        case -1:
            perror("fork");
            break;
            
        case 0:
            close(listener);
            while(1)
            {
                bytes_read = recv(sock, buf, 1024, 0);
                if(bytes_read <= 0) break;
                send(sock, buf, bytes_read, 0);
            }

            close(sock);
            _exit(0);
            
        default:
            close(sock);
        }
    }
    
    close(listener);

    return 0;
}
int main(int argc, char **argv)
{
    int s,nbytes;
    struct sockaddr_can addr;
    struct ifreq ifr;

    struct {
      struct bcm_msg_head msg_head;
      struct can_frame frame[4];
    } txmsg, rxmsg;

    if ((s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM)) < 0) {
	perror("socket");
	return 1;
    }

    addr.can_family = PF_CAN;
    strcpy(ifr.ifr_name, "vcan2");
    ioctl(s, SIOCGIFINDEX, &ifr);
    addr.can_ifindex = ifr.ifr_ifindex;

    if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
	perror("connect");
	return 1;
    }

    txmsg.msg_head.opcode  = RX_SETUP;
    txmsg.msg_head.can_id  = 0x042;
    txmsg.msg_head.flags   = SETTIMER|RX_FILTER_ID;
    txmsg.msg_head.ival1.tv_sec = 4;
    txmsg.msg_head.ival1.tv_usec = 0;
    txmsg.msg_head.ival2.tv_sec = 2;
    txmsg.msg_head.ival2.tv_usec = 0;
    txmsg.msg_head.nframes = 0;

    printf("<*>Writing RX_SETUP with RX_FILTER_ID for can_id <%03X>\n",
	   txmsg.msg_head.can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    /* obsolete for TX_SEND ... */
#if 0
    txmsg.msg_head.can_id  = 0x43;
    txmsg.msg_head.flags   = SETTIMER|STARTTIMER|TX_CP_CAN_ID;
    txmsg.msg_head.count = 0;
    txmsg.msg_head.ival1.tv_sec = 0;
    txmsg.msg_head.ival1.tv_usec = 0;
    txmsg.msg_head.ival2.tv_sec = 0;
    txmsg.msg_head.ival2.tv_usec = 0;
#endif
    txmsg.frame[0].can_id    = 0x43;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<2>Writing TX_SEND with wrong can_id <%03X>\n",
	   txmsg.frame[0].can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<3>Writing TX_SEND with correct can_id <%03X>\n",
	   txmsg.frame[0].can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<3>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    /* growing number of nframes => RX_DELETE instead of simple update */
    txmsg.msg_head.opcode  = RX_DELETE;
    txmsg.msg_head.can_id  = 0x042; /* everything we need for RX_DELETE */

    printf("<*>Writing RX_DELETE for can_id <%03X>\n",
	   txmsg.msg_head.can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = RX_SETUP;
    txmsg.msg_head.can_id  = 0x042;
    txmsg.msg_head.flags   = SETTIMER|RX_CHECK_DLC;
    txmsg.msg_head.ival1.tv_sec = 4;
    txmsg.msg_head.ival1.tv_usec = 0;
    txmsg.msg_head.ival2.tv_sec = 2;
    txmsg.msg_head.ival2.tv_usec = 0;
    txmsg.msg_head.nframes = 1;
    /* txmsg.frame[0].can_dlc   = 8; obsolete for RX_SETUP */
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xFF00000000000000ULL;

    printf("<*>Writing simple RX_SETUP for can_id <%03X> with msgbits 0x%016llX\n",
	   txmsg.msg_head.can_id, U64_DATA(&txmsg.frame[0]));

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<5>Writing TX_SEND with correct can_id <%03X>\n",
	   txmsg.frame[0].can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<5>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<6>Writing TX_SEND with correct can_id <%03X> ",
	   txmsg.frame[0].can_id);
    printf("no changed data\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    /* no change here */

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<7>Writing TX_SEND with correct can_id <%03X> ",
	   txmsg.frame[0].can_id);
    printf("changed relevant msgbits\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<7>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<8>Writing TX_SEND with correct can_id <%03X> ",
	   txmsg.frame[0].can_id);
    printf("changed irrelevant msgbits\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 7;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xdeadbeefdeadbeefULL;

    printf("<9>Writing TX_SEND with correct can_id <%03X> ",
	   txmsg.frame[0].can_id);
    printf("changed Data Length Code DLC\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<9>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    /* no problems ;-) but NOW we try MUX messages ... and timeouts */

    /* growing number of nframes => RX_DELETE instead of simple update */
    txmsg.msg_head.opcode  = RX_DELETE;
    txmsg.msg_head.can_id  = 0x042; /* everything we need for RX_DELETE */

    printf("<*>Writing RX_DELETE for can_id <%03X>\n",
	   txmsg.msg_head.can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = RX_SETUP;
    txmsg.msg_head.can_id  = 0x042;
    txmsg.msg_head.flags   = SETTIMER|RX_CHECK_DLC;
    txmsg.msg_head.ival1.tv_sec = 4;
    txmsg.msg_head.ival1.tv_usec = 0;
    txmsg.msg_head.ival2.tv_sec = 2;
    txmsg.msg_head.ival2.tv_usec = 0;
    txmsg.msg_head.nframes = 3;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0xFF00000000000000ULL;
    U64_DATA(&txmsg.frame[1]) = (__u64) 0x01000000000000FFULL;
    U64_DATA(&txmsg.frame[2]) = (__u64) 0x02000000000000FFULL;

    printf("<*>Writing multiplex RX_SETUP for can_id <%03X>\n",
	   txmsg.msg_head.can_id);

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");


    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x4200000000000000ULL;

    printf("<A>Writing TX_SEND with wrong MUX ID 42\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0100000000000000ULL;

    printf("<B>Writing TX_SEND with correct MUX ID 01\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<B>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0100000000000000ULL;

    printf("<C>Writing TX_SEND with correct MUX ID 01 but no data change\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0100001234567800ULL;

    printf("<D>Writing TX_SEND with correct MUX ID 01 but no relevant data change\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0100001234567801ULL;

    printf("<E>Writing TX_SEND with correct MUX ID 01 with relevant data change\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<E>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0200000000000000ULL;

    printf("<F>Writing TX_SEND with correct MUX ID 02\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<F>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 8;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0200000000000001ULL;

    printf("<10>Writing TX_SEND with correct MUX ID 02 with relevant data change\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<10>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 7;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0200000000000001ULL;

    printf("<11>Writing TX_SEND with correct MUX ID 02 no data change but DLC\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_CHANGED &&
	nbytes == sizeof(struct bcm_msg_head) + sizeof(struct can_frame) &&
	rxmsg.msg_head.can_id == 0x42 && rxmsg.frame[0].can_id == 0x42) {
      printf("<11>Received correct RX_CHANGED message for can_id <%03X> >> OK!\n",
	     rxmsg.frame[0].can_id);
    }

    txmsg.msg_head.opcode  = TX_SEND;
    txmsg.msg_head.nframes = 1;
    txmsg.frame[0].can_id    = 0x42;
    txmsg.frame[0].can_dlc   = 7;
    U64_DATA(&txmsg.frame[0]) = (__u64) 0x0300000000000001ULL;

    printf("<12>Writing TX_SEND with wrong MUX ID 03\n");

    if (write(s, &txmsg, sizeof(txmsg)) < 0)
      perror("write");

    if ((nbytes = read(s, &rxmsg, sizeof(rxmsg))) < 0)
      perror("read");

    if (rxmsg.msg_head.opcode == RX_TIMEOUT &&
	nbytes == sizeof(struct bcm_msg_head) &&
	rxmsg.msg_head.can_id == 0x42) {
      printf("<-->Received correct RX_TIMEOUT message for can_id <%03X> >> OK!\n",
	     rxmsg.msg_head.can_id);
    }

    close(s);

    return 0;
}
Example #26
0
void main(void)
{

int socket_fd;
struct sockaddr_in sa,ra;

int recv_data; char data_buffer[80]; /* Creates an TCP socket (SOCK_STREAM) with Internet Protocol Family (PF_INET).
 * Protocol family and Address family related. For example PF_INET Protocol Family and AF_INET family are coupled.
*/

socket_fd = socket(PF_INET, SOCK_STREAM, 0);

if ( socket_fd < 0 )
{

printf("socket call failed");
exit(0);
}

memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr(SENDER_IP_ADDR);
sa.sin_port = htons(SENDER_PORT_NUM);


/* Bind the TCP socket to the port SENDER_PORT_NUM and to the current
* machines IP address (Its defined by SENDER_IP_ADDR).
* Once bind is successful for UDP sockets application can operate
* on the socket descriptor for sending or receiving data.
*/
if (bind(socket_fd, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) == -1)
{
printf("Bind to Port Number %d ,IP address %s failed\n",SENDER_PORT_NUM,SENDER_IP_ADDR);
close(socket_fd);
exit(1);
}
/* Receiver connects to server ip-address. */

memset(&ra, 0, sizeof(struct sockaddr_in));
ra.sin_family = AF_INET;
ra.sin_addr.s_addr = inet_addr(SERVER_IP_ADDRESS);
ra.sin_port = htons(SERVER_PORT_NUM);


if(connect(socket_fd,(struct sockaddr_in*)&ra,sizeof(struct sockaddr_in)) < 0)
{

printf("connect failed \n");
close(socket_fd);
exit(2);
}
recv_data = recv(socket_fd,data_buffer,sizeof(data_buffer),0);
if(recv_data < 0)
{

printf("recv failed \n");
close(socket_fd);
exit(2);
}
data_buffer[recv_data] = '\0';
printf("received data: %s\n",data_buffer);

close(socket_fd);
}
void *threadfunction2() {
	int socketFD;
	int prev;
	int ackNum;
	double ts;
	char ack[12];

	
	struct addrinfo hints;
	struct addrinfo *servinfo;
	struct sockaddr_in clientinfo;
	int clientinfolen;

	
	//Get connection info
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE;


	socketFD = socket(AF_INET, SOCK_DGRAM, 0);
	if (socketFD < 0){
		printf("Error: Could not get socket.\n");
		exit(1);
	}
	
	if(getaddrinfo("10.10.66.90", "56700", &hints, &servinfo) != 0 || servinfo == NULL){
	    printf("Error: Could not get connection info with router.\n");
	    exit(1);
	}


	if(bind(socketFD, servinfo->ai_addr, servinfo->ai_addrlen) < 0){
		printf("Error: Could not bind socket.\n");
		exit(1);
	}
	
	
	prev = 1;
	while (1) {
		clientinfolen = sizeof(struct sockaddr_in);

		if (recvfrom(socketFD, &ack, 12, 0, &clientinfo, &clientinfolen) == -1) {
			printf("Receiving failed!\n");
			exit(1);
		}

		memcpy(&ackNum,&ack,4);
		memcpy(&ts, ack+4, 8);
		//printf("%lf\n", ts);
		TIME_OUT = TIME_OUT * 0.875 + 0.125 * (clock()/(double)CLOCKS_PER_SEC - ts);
        //printf("%lf\n",TIME_OUT);
		

        

		indicator += 1;
		

		if (ackNum == prev) {
        
			if ((WINDOW_SIZE / 2)<=1) {
                WINDOW_SIZE = 1;
            } else if (ackNum !=1){
                WINDOW_SIZE /= 2;
            }
		} else {
			if (ackNum-prev >= WINDOW_SIZE) {
                
				prev = ackNum;
				WINDOW_SIZE += 1;
			}
		}
        if (numACK < ackNum) {
            numACK = ackNum;
        }
        //printf("%d\n",WINDOW_SIZE);
	}
}
Example #28
0
S32 start_net(S32& socket_out, int& nPort) 
{			
	// Create socket, make non-blocking
    // Init WinSock 
	int nRet;
	int hSocket;

	int snd_size = SEND_BUFFER_SIZE;
	int rec_size = RECEIVE_BUFFER_SIZE;
	int buff_size = 4;
 
	// Initialize windows specific stuff
	if(WSAStartup(0x0202, &stWSAData))
	{
		S32 err = WSAGetLastError();
		WSACleanup();
		LL_WARNS("AppInit") << "Windows Sockets initialization failed, err " << err << LL_ENDL;
		return 1;
	}

	// Get a datagram socket
    hSocket = (int)socket(AF_INET, SOCK_DGRAM, 0);
    if (hSocket == INVALID_SOCKET)
	{
		S32 err = WSAGetLastError();
		WSACleanup();
		LL_WARNS("AppInit") << "socket() failed, err " << err << LL_ENDL;
		return 2;
	}

	// 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);

	S32 attempt_port = nPort;
	LL_DEBUGS("AppInit") << "attempting to connect on port " << attempt_port << LL_ENDL;
	nRet = bind(hSocket, (struct sockaddr*) &stLclAddr, sizeof(stLclAddr));

	if (nRet == SOCKET_ERROR)
	{
		// If we got an address in use error...
		if (WSAGetLastError() == WSAEADDRINUSE)
		{
			// 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);
				LL_DEBUGS("AppInit") << "trying port " << attempt_port << LL_ENDL;
				nRet = bind(hSocket, (struct sockaddr*) &stLclAddr, sizeof(stLclAddr));

				if (!(nRet == SOCKET_ERROR && 
					WSAGetLastError() == WSAEADDRINUSE))
				{
					break;
				}
			}

			if (nRet == SOCKET_ERROR)
			{
				LL_WARNS("AppInit") << "startNet() : Couldn't find available network port." << LL_ENDL;
				// Fail gracefully here in release
				return 3;
			}
		}
		else
		// Some other socket error
		{
			LL_WARNS("AppInit") << llformat("bind() port: %d failed, Err: %d\n", nPort, WSAGetLastError()) << LL_ENDL;
			// Fail gracefully in release.
			return 4;
		}
	}

	sockaddr_in socket_address;
	S32 socket_address_size = sizeof(socket_address);
	getsockname(hSocket, (SOCKADDR*) &socket_address, &socket_address_size);
	attempt_port = ntohs(socket_address.sin_port);

	LL_INFOS("AppInit") << "connected on port " << attempt_port << LL_ENDL;
	nPort = attempt_port;
	
	// Set socket to be non-blocking
	unsigned long argp = 1;
	nRet = ioctlsocket (hSocket, FIONBIO, &argp);
	if (nRet == SOCKET_ERROR) 
	{
		printf("Failed to set socket non-blocking, Err: %d\n", 
		WSAGetLastError());
	}

	// set a large receive buffer
	nRet = setsockopt(hSocket, SOL_SOCKET, SO_RCVBUF, (char *)&rec_size, buff_size);
	if (nRet)
	{
		LL_INFOS("AppInit") << "Can't set receive buffer size!" << LL_ENDL;
	}

	nRet = setsockopt(hSocket, SOL_SOCKET, SO_SNDBUF, (char *)&snd_size, buff_size);
	if (nRet)
	{
		LL_INFOS("AppInit") << "Can't set send buffer size!" << LL_ENDL;
	}

	getsockopt(hSocket, SOL_SOCKET, SO_RCVBUF, (char *)&rec_size, &buff_size);
	getsockopt(hSocket, SOL_SOCKET, SO_SNDBUF, (char *)&snd_size, &buff_size);

	LL_DEBUGS("AppInit") << "startNet - receive buffer size : " << rec_size << LL_ENDL;
	LL_DEBUGS("AppInit") << "startNet - send buffer size    : " << snd_size << LL_ENDL;

	//  Setup a destination address
	char achMCAddr[MAXADDRSTR] = " ";	/* 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;
}
Example #29
0
int main (int argc, char *argv[])
{
	ROT *my_rot;		/* handle to rot (instance) */
	rot_model_t my_model = ROT_MODEL_DUMMY;

	int retcode;		/* generic return code from functions */

	int verbose = 0;
	int show_conf = 0;
	int dump_caps_opt = 0;
	const char *rot_file=NULL;
	int serial_rate = 0;
	char conf_parms[MAXCONFLEN] = "";

	struct addrinfo hints, *result;
	int sock_listen;
	int reuseaddr = 1;

	while(1) {
		int c;
		int option_index = 0;

		c = getopt_long (argc, argv, SHORT_OPTIONS,
			long_options, &option_index);
		if (c == -1)
			break;

		switch(c) {
			case 'h':
				usage();
				exit(0);
			case 'V':
				version();
				exit(0);
			case 'm':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				my_model = atoi(optarg);
				break;
			case 'r':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				rot_file = optarg;
				break;
			case 's':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				serial_rate = atoi(optarg);
				break;
			case 'C':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				if (*conf_parms != '\0')
					strcat(conf_parms, ",");
				strncat(conf_parms, optarg, MAXCONFLEN-strlen(conf_parms));
				break;
			case 't':
				if (!optarg) {
					usage();        /* wrong arg count */
					exit(1);
				}
				portno = optarg;
				break;
			case 'T':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				src_addr = optarg;
				break;
			case 'v':
				verbose++;
				break;
			case 'L':
				show_conf++;
				break;
			case 'l':
				list_models();
				exit(0);
			case 'u':
				dump_caps_opt++;
				break;
			case 'e':
				opt_end = 1;
				fprintf(stderr, "-e|--end-marker option is deprecated!\nPlease consider using the Extended Response protocol instead.\n");
				break;
			default:
				usage();	/* unknown option? */
				exit(1);
		}
	}

	rig_set_debug(verbose);

	rig_debug(RIG_DEBUG_VERBOSE, "rotctld, %s\n", hamlib_version);
	rig_debug(RIG_DEBUG_VERBOSE, "Report bugs to "
			"<hamlib-developer@lists.sourceforge.net>\n\n");

  	my_rot = rot_init(my_model);

	if (!my_rot) {
		fprintf(stderr, "Unknown rot num %d, or initialization error.\n",
						my_model);
		fprintf(stderr, "Please check with --list option.\n");
		exit(2);
	}

	retcode = set_conf(my_rot, conf_parms);
	if (retcode != RIG_OK) {
		fprintf(stderr, "Config parameter error: %s\n", rigerror(retcode));
		exit(2);
	}

	if (rot_file)
		strncpy(my_rot->state.rotport.pathname, rot_file, FILPATHLEN - 1);

	/* FIXME: bound checking and port type == serial */
	if (serial_rate != 0)
		my_rot->state.rotport.parm.serial.rate = serial_rate;

	/*
	 * print out conf parameters
	 */
	if (show_conf) {
		rot_token_foreach(my_rot, print_conf_list, (rig_ptr_t)my_rot);
	}

	/*
	 * print out conf parameters, and exits immediately
	 * We may be interested only in only caps, and rig_open may fail.
	 */
	if (dump_caps_opt) {
		dumpcaps_rot(my_rot, stdout);
		rot_cleanup(my_rot); /* if you care about memory */
		exit(0);
	}

	retcode = rot_open(my_rot);
	if (retcode != RIG_OK) {
	  	fprintf(stderr,"rot_open: error = %s \n", rigerror(retcode));
		exit(2);
	}

	if (verbose > 0)
		printf("Opened rot model %d, '%s'\n", my_rot->caps->rot_model,
						my_rot->caps->model_name);

	rig_debug(RIG_DEBUG_VERBOSE, "Backend version: %s, Status: %s\n",
			my_rot->caps->version, rig_strstatus(my_rot->caps->status));

#ifdef __MINGW32__
# ifndef SO_OPENTYPE
#  define SO_OPENTYPE     0x7008
# endif
# ifndef SO_SYNCHRONOUS_NONALERT
#  define SO_SYNCHRONOUS_NONALERT 0x20
# endif
# ifndef INVALID_SOCKET
#  define INVALID_SOCKET -1
# endif

	WSADATA wsadata;
	if (WSAStartup(MAKEWORD(1,1), &wsadata) == SOCKET_ERROR) {
		fprintf(stderr,"WSAStartup socket error\n");
		exit(1);
	}

	int sockopt = SO_SYNCHRONOUS_NONALERT;
	setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&sockopt, sizeof(sockopt));
#endif

	/*
	 * Prepare listening socket
	 */
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
	hints.ai_socktype = SOCK_STREAM;/* TCP socket */
	hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
	hints.ai_protocol = 0;          /* Any protocol */

	retcode = getaddrinfo(src_addr, portno, &hints, &result);
	if (retcode != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retcode));
		exit(2);
	}

	sock_listen = socket(result->ai_family, result->ai_socktype,
			result->ai_protocol);
	if (sock_listen < 0)  {
		perror("ERROR opening socket");
		exit(1);
	}

	if (setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR,
				(char *)&reuseaddr,sizeof(reuseaddr)) < 0) {
		rig_debug(RIG_DEBUG_ERR, "setsockopt: %s\n", strerror(errno));
		exit (1);
	}
	if (bind(sock_listen, result->ai_addr, result->ai_addrlen) < 0) {
		rig_debug(RIG_DEBUG_ERR, "binding: %s\n", strerror(errno));
		exit (1);
	}

	freeaddrinfo(result);           /* No longer needed */

	if (listen(sock_listen,4) < 0) {
		rig_debug(RIG_DEBUG_ERR, "listening: %s\n", strerror(errno));
		exit (1);
	}

	/*
	 * main loop accepting connections
	 */
	do {
#ifdef HAVE_PTHREAD
		pthread_t thread;
		pthread_attr_t attr;
#endif
		struct handle_data *arg;

		arg = malloc(sizeof(struct handle_data));
		if (!arg) {
			rig_debug(RIG_DEBUG_ERR, "malloc: %s\n", strerror(errno));
			exit (1);
		}

		arg->rot = my_rot;
		arg->clilen = sizeof(arg->cli_addr);
		arg->sock = accept(sock_listen, (struct sockaddr *) &arg->cli_addr,
				&arg->clilen);
		if (arg->sock < 0) {
			rig_debug(RIG_DEBUG_ERR, "accept: %s\n", strerror(errno));
			break;
		}

		rig_debug(RIG_DEBUG_VERBOSE, "Connection opened from %s:%d\n",
				inet_ntoa(arg->cli_addr.sin_addr),
				ntohs(arg->cli_addr.sin_port));

#ifdef HAVE_PTHREAD
		pthread_attr_init(&attr);
		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

		retcode = pthread_create(&thread, &attr, handle_socket, arg);
		if (retcode != 0) {
			rig_debug(RIG_DEBUG_ERR, "pthread_create: %s\n", strerror(retcode));
			break;
		}
#else
		handle_socket(arg);
#endif
	}
	while (retcode == 0);

	rot_close(my_rot); /* close port */
	rot_cleanup(my_rot); /* if you care about memory */

#ifdef __MINGW32__
	WSACleanup();
#endif

	return 0;
}
Example #30
0
int main(int argc, char ** argv)
{
	int sockfd, new_fd;
	struct addrinfo hints, *servinfo, *p ;
	struct sockaddr_storage their_addr;
	socklen_t sin_size ;
	struct sigaction sa;
	int yes =1;
	
	//char buf[MAXDATASIZE] ;
	int bytes_rcv = 0 ;
	int bytes_snd = 0 ;

	char s[INET6_ADDRSTRLEN];
	int rv;

	int wait_for_message = -1 ;

		
	//initializing variables for use in select function
	fd_set fdset;
	int client_connections[MAXCLIENTS] = {0};
	int max_fd ;

	if(argc != 2)
	{
		printf("<usage>: ./server 5000\n");
		exit(0 );
	}

	memset(&hints,0 ,sizeof hints);
	//setting up the information about the type of the address to query
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;


	if((rv = getaddrinfo(NULL,argv[1],&hints,&servinfo)) != 0)
	{
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}


	sockfd = socket(servinfo->ai_family,servinfo->ai_socktype,servinfo->ai_protocol);
	if (sockfd == -1)
	{
		printf("could not create socket\n");	
		return 1;
	}
	
	if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, &yes,sizeof (int)) == -1)
	{
		printf("setsockopt\n");
		exit(1);
	}
	if (bind(sockfd,servinfo->ai_addr, servinfo->ai_addrlen) == -1)
	{
		close(sockfd);
		printf("socket:bind\n");
		exit(1);
	}
	
	freeaddrinfo(servinfo); //done with the job of this structure
	
	if(listen(sockfd,BACKLOG) == -1)
	{
		printf("listen\n");	
		exit(1);
	}
	

//	initializeFD(fdset,sockfd,client_connections);
	sin_size = sizeof their_addr ;
//	max_fd = sockfd ;
	
	int i = 0 ; //counter variable
	int sd ; // temporary holdder	

	int clients_to_read = 0 ;

	printf("Starting select loop, fdmax %d\n",sockfd) ;
	while(1)
	{

		/* adding logic for using select function*/				
		FD_ZERO(&fdset) ;
	        FD_SET(sockfd,&fdset) ;
		max_fd = sockfd ;
        	for(i = 0; i <MAXCLIENTS ;i ++)
        	{
               		sd = client_connections[i];


			if(sd >0)
			{
		               	FD_SET(sd,&fdset);
			}
		
		
			if (max_fd < sd)
			{
				max_fd = sd;
			}
			
        	}

		clients_to_read = select (max_fd +1 ,&fdset,NULL,NULL,NULL) ; // wait till request arrives

		//if (clients_to_read > 0)
				
			if (FD_ISSET(sockfd, &fdset) != 0)	
			{
				new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
				if (new_fd == -1)
				{
					printf("accept error\n");
					continue ;
				}

				inet_ntop(their_addr.ss_family,
					get_in_addr((struct sockaddr *)&their_addr),
					s, sizeof s);
				printf("server: got connection from %s and socket %d\n", s,new_fd);
				

				// adding new connection to clients array
				for (i = 0 ; i<MAXCLIENTS; i++)	
				{
					if (client_connections[i] == 0)
					{
						client_connections[i] = new_fd ;
						break ;
					}
						
				}
			
				
			}		
			
			
			for(i = 0 ; i< MAXCLIENTS ; i++)
			{
				if (FD_ISSET(client_connections[i], &fdset) !=0)
				{
					printf("In select loop: socket %d is ready to read\n", client_connections[i]) ;
					handle_client_connection(client_connections[i],client_connections,i) ;
				}
			}
			
		
		
	}
		
	return 0 ;
}