Esempio n. 1
0
/**
 * Function: senddata
 * Description: 串口客户端UDP发送数据的接口函数
 * @param conn 当前UDP的连接
 * @param serial_no UDP连接对应的串口号
 * @param data_length 要发送的数据长度
**/
uint8_t senddata(struct udp_pcb *conn,uint8_t serial_no,uint32_t data_length) {
    uint32_t send_length = 0;
	struct pbuf *udp_data_packet;
	uint32_t loc = 0;
	err_t err_status;
	do {
		
		if(data_length >= UDP_MSS) {
            send_length = UDP_MSS;
        } else {
            send_length = data_length;
        }
		udp_data_packet = pbuf_alloc(PBUF_RAW,send_length,PBUF_RAM);
		if(!udp_data_packet){
			printf("serial udp memory allocate\n\r");
			return 0;
		}
        memset(udp_data_packet->payload,0,send_length);
		memcpy(udp_data_packet->payload,&serial_client.client_queue_data_buf[serial_no][loc],send_length);
		err_status = udp_send(conn,udp_data_packet);
		loc += send_length;
        data_length -= send_length;
		if(udp_data_packet){
			pbuf_free(udp_data_packet);
			udp_data_packet = NULL;
		}
    } while(data_length > 0);
	if(serial_client.client_queue_data_buf[serial_no]){
		free(serial_client.client_queue_data_buf[serial_no]);
		serial_client.client_queue_data_buf[serial_no] = NULL;
	}
	return 1;
}
Esempio n. 2
0
File: twatc.c Progetto: vrld/twat
void receive_tweet(char* buffer, struct sockaddr_in* server)
{
    struct sockaddr_in client;
    int transfered = 0, timeoutcount = 0;

    /* Get message from message server */
    if (!udp_send(sock, "Gimmeh!", server, sizeof(struct sockaddr_in)))
        error_and_exit("Cannot send message to server", __FILE__, __LINE__);

    do {
        transfered = udp_receive(sock, buffer, BUFSIZE, &client, sizeof(client));
        if (transfered == -1) 
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK) 
            {
                ++timeoutcount;
                if (timeoutcount >= MAX_TIMEOUTS) 
                {
                    printf("Maximum timeouts exceeded. Server is considered dead.");
                    exit(0);
                }
                printf("Server timed out (%d).\n", timeoutcount);
            }

            error_and_exit("Cannot read from server", __FILE__, __LINE__);
        } 
        else if (transfered == 0) 
        {
            error_and_exit("Server has shut down", __FILE__, __LINE__);
        }
    } while (transfered <= 0); 
    if (server->sin_addr.s_addr != client.sin_addr.s_addr)
        error_and_exit("Received message from unexpected server", __FILE__, __LINE__);
}
Esempio n. 3
0
File: rtp.c Progetto: hbowden/re
/**
 * Send an RTP packet to a peer
 *
 * @param rs     RTP Socket
 * @param dst    Destination address
 * @param ext    Extension bit
 * @param marker Marker bit
 * @param pt     Payload type
 * @param ts     Timestamp
 * @param mb     Payload buffer
 *
 * @return 0 for success, otherwise errorcode
 */
int rtp_send(struct rtp_sock *rs, const struct sa *dst, bool ext,
	     bool marker, uint8_t pt, uint32_t ts, struct mbuf *mb)
{
	size_t pos;
	int err;

	if (!rs || !mb)
		return EINVAL;

	if (mb->pos < RTP_HEADER_SIZE) {
		DEBUG_WARNING("rtp_send: buffer must have space for"
			      " rtp header (pos=%u, end=%u)\n",
			      mb->pos, mb->end);
		return EBADMSG;
	}

	mbuf_advance(mb, -RTP_HEADER_SIZE);

	pos = mb->pos;

	err = rtp_encode(rs, ext, marker, pt, ts, mb);
	if (err)
		return err;

	if (rs->rtcp)
		rtcp_sess_tx_rtp(rs->rtcp, ts, mbuf_get_left(mb));

	mb->pos = pos;

	return udp_send(rs->sock_rtp, dst, mb);
}
Esempio n. 4
0
int main (void)
{
    zctx_t *ctx = zctx_new ();
    udp_t *udp = udp_new (PING_PORT_NUMBER);
    
    byte buffer [PING_MSG_SIZE];
    zmq_pollitem_t pollitems [] = {{ NULL, udp_handle (udp), ZMQ_POLLIN, 0 }};
    
    //  Send first ping right away
    uint64_t ping_at = zclock_time ();
    
    while (!zctx_interrupted) {
        long timeout = (long) (ping_at - zclock_time ());
        if (timeout < 0)
            timeout = 0;
        if (zmq_poll (pollitems, 1, timeout * ZMQ_POLL_MSEC) == -1)
            break;              //  Interrupted

        //  Someone answered our ping
        if (pollitems [0].revents & ZMQ_POLLIN)
            udp_recv (udp, buffer, PING_MSG_SIZE);
        
        if (zclock_time () >= ping_at) {
            puts ("Pinging peers...");
            buffer [0] = '!';
            udp_send (udp, buffer, PING_MSG_SIZE);
            ping_at = zclock_time () + PING_INTERVAL;
        }
    }
    udp_destroy (&udp);
    zctx_destroy (&ctx);
    return 0;
}
Esempio n. 5
0
/**
 * Send some data on a RAW or UDP pcb contained in a netconn
 * Called from netconn_send
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_send(struct api_msg_msg *msg)
{
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if (msg->conn->pcb.tcp != NULL) {
      switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
      case NETCONN_RAW:
        if (msg->msg.b->addr == NULL) {
          msg->conn->err = raw_send(msg->conn->pcb.raw, msg->msg.b->p);
        } else {
          msg->conn->err = raw_sendto(msg->conn->pcb.raw, msg->msg.b->p, msg->msg.b->addr);
        }
        break;
#endif
#if LWIP_UDP
      case NETCONN_UDP:
        if (msg->msg.b->addr == NULL) {
          msg->conn->err = udp_send(msg->conn->pcb.udp, msg->msg.b->p);
        } else {
          msg->conn->err = udp_sendto(msg->conn->pcb.udp, msg->msg.b->p, msg->msg.b->addr, msg->msg.b->port);
        }
        break;
#endif /* LWIP_UDP */
      default:
        break;
      }
    }
  }
  TCPIP_APIMSG_ACK(msg);
}
Esempio n. 6
0
// This is a very weird function, look at udpCheckReceiveFork() in matlab.c for the "why"
int udpmsg_receive(udpmsg *packet)
 {
	 char recv_buf[MAXMSGLENGTH+10];
	 char senderIP[16]; // "xxx.xxx.xxx.xxx\0"
	 int ret = 0;

	 if(udp_check(0)) {

		 udp_read(recv_buf, sizeof(recv_buf), senderIP);
		 //	printf("%s\n", senderIP);
		 // First if clause determines whether message is from Psychtoolbox
		 if (!strcmp(senderIP, macIP)) {
			 if(strlen(recv_buf)>10 && recv_buf[9]==' ' && strcmp(recv_buf,last_recv)!=0) {
				 strcpy(last_recv, recv_buf);
				 strncpy(packet->id, recv_buf, 9);
				 packet->id[9] = 0;
				 strcpy(packet->msg, recv_buf+10);
				 if (strcmp(packet->msg,"RECEIVED")==0)
				   packet->received = 1;
				 else if (strcmp(packet->msg,"EXECUTED")==0)
				   packet->executed = 1;
				 else {
					 /* if it is a new message confirm its receipt */
					 strcpy(recv_buf+10, "RECEIVED");
					 udp_send(recv_buf, macIP);
				 }
				 
				 ret = 1;
			 }       
		 }
	 }
	 return ret;
 }
Esempio n. 7
0
static void
do_send(struct api_msg_msg *msg)
{
  if (msg->conn->pcb.tcp != NULL) {
    switch (msg->conn->type) {
#if LWIP_RAW
    case NETCONN_RAW:
      raw_send(msg->conn->pcb.raw, msg->msg.p);
      break;
#endif
#if LWIP_UDP
    case NETCONN_UDPLITE:
      /* FALLTHROUGH */
    case NETCONN_UDPNOCHKSUM:
      /* FALLTHROUGH */
    case NETCONN_UDP:
      udp_send(msg->conn->pcb.udp, msg->msg.p);
      break;
#endif /* LWIP_UDP */
    case NETCONN_TCP:
      break;
    }
  }
  sys_mbox_post(msg->conn->mbox, NULL);
}
Esempio n. 8
0
int udp_broadcast (const char *address,
                   unsigned int port,
                   const paxos_message_t *message)
{
  udp_client_t client;
  int sock;
  int ret;

  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    return(-1);

  ret = 1;
  if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &ret, sizeof(int)) < 0) {
    close(sock);
    return(-1);
  }

  memset(&(client.addr), 0, sizeof(struct sockaddr_in));
  client.addr.sin_family = AF_INET;
  client.addr.sin_addr.s_addr = inet_addr(address);
  //client.addr.sin_addr.s_addr = inet_addr("127.255.255.255");
  //addr.sin_addr.s_addr = inet_addr("255.255.255.255");
  client.addr.sin_port = htons(port);

  client.addrlen = sizeof(struct sockaddr_in);
  ret = udp_send(sock, &client, message);

  close(sock);
  return(ret != sizeof(paxos_message_t));
}
Esempio n. 9
0
socket_error_t lwipv4_socket_send(struct socket *socket, const void * buf, const size_t len)
{
    err_t err = ERR_VAL;
    switch(socket->family) {
    case SOCKET_DGRAM: {
        struct pbuf *pb = pbuf_alloc(PBUF_TRANSPORT,len,PBUF_RAM);
        socket_event_t e;
        socket_api_handler_t handler = socket->handler;
        err = pbuf_take(pb, buf, len);
        if (err != ERR_OK)
            break;
        err = udp_send(socket->impl, pb);
        pbuf_free(pb);
        if (err != ERR_OK)
            break;
        //Notify the application that the transfer is queued at the MAC layer
        e.event = SOCKET_EVENT_TX_DONE;
        e.sock = socket;
        e.i.t.sentbytes = len;
        socket->event = &e;
        handler();
        socket->event = NULL;
        break;
    }
    case SOCKET_STREAM:
        err = tcp_write(socket->impl,buf,len,TCP_WRITE_FLAG_COPY);
        break;
    }
    return lwipv4_socket_error_remap(err);
}
Esempio n. 10
0
static err_t dhcp_release(struct dhcp_state *state)
{
  err_t result;
  u16_t msecs;
  DEBUGF(DHCP_DEBUG, ("dhcp_release()\n"));
  // and idle DHCP client
  dhcp_set_state(state, DHCP_OFF);

  // create and initialize the DHCP message header
  result = dhcp_create_request(state);
  if (result == ERR_OK)
  {
    dhcp_option(state, DHCP_OPTION_MESSAGE_TYPE, DHCP_OPTION_MESSAGE_TYPE_LEN);
    dhcp_option_byte(state, DHCP_RELEASE);

    dhcp_option_trailer(state);

    pbuf_realloc(state->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + state->options_out_len);

    udp_bind(state->pcb, IP_ADDR_ANY, DHCP_CLIENT_PORT);
    udp_connect(state->pcb, &state->server_ip_addr, DHCP_SERVER_PORT);
    udp_send(state->pcb, state->p_out);
    dhcp_delete_request(state);
  }
  state->tries++;
  msecs = state->tries < 10 ? state->tries * 1000 : 10 * 1000;
  state->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS;
  DEBUGF(DHCP_DEBUG, ("dhcp_release(): request timeout %u msecs\n", msecs));
  // remove IP address from interface
  netif_set_ipaddr(state->netif, IP_ADDR_ANY);
  netif_set_gw(state->netif, IP_ADDR_ANY);
  netif_set_netmask(state->netif, IP_ADDR_ANY);
  return result;
}
Esempio n. 11
0
/**
 * Function: send_packet
 * Description: 向NTP服务器发送NTP数据包,请求时间更新
 * @param usd 标志位,目前统一使用1
**/
int send_packet(int usd) {
    //char ntp_header[200];
	struct pbuf *ntp_packet;
	err_t err_result;
	memset(&ntp_client,0,sizeof(ntp_client));
	ntp_packet = pbuf_alloc(PBUF_RAW,sizeof(ntp_client),PBUF_RAM);
	if(!ntp_packet){
		printf("ntp pbuf allocate failed\n\r");
		return -1;
	}
	NTP_Init();
	memset(ntp_packet->payload,0,sizeof(ntp_client));
	memcpy(ntp_packet->payload,(void*)&ntp_client,sizeof(ntp_client));
	
    /*客户端给服务器端发送NTP协议数据包*/
	
	err_result = udp_send(ntp_udp_client,ntp_packet);
	if(err_result == ERR_OK){   //数据发送成功
		//释放pbuf空间
		pbuf_free(ntp_packet);
	}else{
		printf("ntp packet send failed\n\r");
		return -1;
	}
	is_open_ntp_request_timer = 1;
	ntp_send_request_time = sCount;
	//printf("NTP request has sent over\n\r");
}
Esempio n. 12
0
// decline a
static err_t dhcp_decline(struct dhcp_state *state)
{
  err_t result = ERR_OK;
  u16_t msecs;
  DEBUGF(DHCP_DEBUG, ("dhcp_decline()\n"));
  dhcp_set_state(state, DHCP_BACKING_OFF);
  // create and initialize the DHCP message header
  result = dhcp_create_request(state);
  if (result == ERR_OK)
  {
    dhcp_option(state, DHCP_OPTION_MESSAGE_TYPE, DHCP_OPTION_MESSAGE_TYPE_LEN);
    dhcp_option_byte(state, DHCP_DECLINE);

    dhcp_option(state, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
    dhcp_option_short(state, 576);

    dhcp_option_trailer(state);
    // resize pbuf to reflect true size of options
    pbuf_realloc(state->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + state->options_out_len);

    udp_bind(state->pcb, IP_ADDR_ANY, DHCP_CLIENT_PORT);
    udp_connect(state->pcb, &state->server_ip_addr, DHCP_SERVER_PORT);
    udp_send(state->pcb, state->p_out);
    dhcp_delete_request(state);
  }
  state->tries++;
  msecs = 10*1000;
  state->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS;
  DEBUGF(DHCP_DEBUG, ("dhcp_decline(): request timeout %u msecs\n", msecs));
  return result;
}
Esempio n. 13
0
/*
 * 函数名:updd_Send
 * 描述  :发送udp数据包
 * 输入  :无
 * 输出  : 无
 * 调用  :外部调用
 */
void udpd_Send(void)
{
	struct udp_pcb *UdpPcb; 
  struct ip_addr ipaddr; 
  struct pbuf *p;
	err_t err = ERR_Mine;	//测试用
	
	p = pbuf_alloc(PBUF_RAW,sizeof(UDPData),PBUF_RAM); 
  p->payload=(void *)UDPData; 
   
	UdpPcb = udp_new(); 
	udp_bind(UdpPcb,IP_ADDR_ANY,6000);       /* 绑定本地IP 地址 */ 
  IP4_ADDR(&ipaddr,192,168,1,122); 
  
  err = udp_connect(UdpPcb,&ipaddr,6001);   /* 连接远程主机 */ 	

	if(err == ERR_OK)
	{
		err = ERR_Mine;	//测试用
		err = udp_send(UdpPcb, p);
	}
	
	udp_disconnect(UdpPcb);
	pbuf_free(p);
	udp_remove(UdpPcb);
}
Esempio n. 14
0
int main(int argc, char** argv){

	if(argc != 4  && argc != 2){
		printf("\nSYTAX: <(s)end/(r)ecv> xxx.xxx.xxx.xxx  \"Message (if sending)\"");
		exit(0);
	}

	if(argv[1][0] == 's'){
		char *addr;
		char *msg;
		size_t msg_len = strlen(argv[3])+1;
		int add_len = strlen(argv[2]);
		msg=malloc(msg_len);
		strcpy(msg,argv[3]);
		addr = malloc(add_len);
		memcpy(addr,argv[2],add_len);
		udp_send(addr,d_port,d_port,&msg,&msg_len);
	}
	else if (argv[1][0] == 'r'){
		size_t size;
		size = (size_t) 512;
		char* msg;
		msg = malloc(size);
		udp_listen(d_port,&msg,size);
		printf("Received : \n%s",msg);
	}
	return 0;
}
Esempio n. 15
0
int mgcp_send_dummy(struct mgcp_endpoint *endp)
{
	static char buf[] = { DUMMY_LOAD };

	return udp_send(endp->net_end.rtp.fd, &endp->net_end.addr,
			endp->net_end.rtp_port, buf, 1);
}
Esempio n. 16
0
void client_init(void)
{
    struct udp_pcb *upcb;
    struct pbuf *p;

    SET_IP4_ADDR(&ip_udp_server,UDP_SERVER_IP);
    /* Create a new UDP control block  */
    upcb = udp_new();
    p = pbuf_alloc(PBUF_TRANSPORT, sizeof(Sent), PBUF_RAM);
    p->payload = (void*)Sent;
    upcb->local_port = 5;
    udp_connect(upcb, &ip_udp_server, UDP_SERVER_PORT);
    udp_send(upcb, p);



    /* Reset the upcb */
    udp_disconnect(upcb);

    /* Bind the upcb to any IP address and the UDP_PORT port*/
    udp_bind(upcb, IP_ADDR_ANY, 5);


    udp_recv(upcb, udp_client_callback, NULL);

    /* Free the p buffer */
    pbuf_free(p);

}
Esempio n. 17
0
void *_send(void *args)
{
    (void) args;
    msg_init_queue(_send_msg_queue, MAIN_QUEUE_SIZE);

    char *arg[4];
    char *cmd = "udp_send";
    char *dst = "abcd::1";
    char *port = "8888";
    char rank[12];

    arg[0] = cmd;
    arg[1] = dst;
    arg[2] = port;

    while(1) {
        xtimer_sleep(2);
        if (gnrc_rpl_instances[0].state && gnrc_rpl_instances[0].dodag.my_rank == GNRC_RPL_ROOT_RANK) {
            return NULL;
        }

        if (gnrc_rpl_instances[0].state) {
            memset(rank, 0, sizeof(rank));
            sprintf(rank, "%u", gnrc_rpl_instances[0].dodag.my_rank);
            arg[3] = rank;
            udp_send(4, arg);
        }
    }
    return NULL;
}
Esempio n. 18
0
extern int send_rescueack(unsigned short no, unsigned short lo)
{
	ebuf_t *buf = NULL;
	int acksocket;
	char tftpnull;
	int res, i;

	/*
	 * Open a UDP socket to the TFTP server
	 */
	acksocket = udp_socket(UDP_PROTO_TFTP);
	res = udp_bind(acksocket, 69);
	if (res < 0) {
		return res;
	}
	udp_connect(acksocket, ackport);
	for (i = 0; i < 1; i++) {
		buf = udp_alloc();
		if (!buf)
			return -1;
		/*
		 * Send the data
		 */
		ebuf_append_u16_be(buf, no);
		ebuf_append_u16_be(buf, lo);
		ebuf_append_bytes(buf,&tftpnull, 0);
		udp_send(acksocket ,buf, tftpipto);
	}
	if (buf)
		udp_free(buf);
	udp_close(acksocket);
	return 0;
}
void mdns_probe()
{
	len_self = _update_hook_self(config.name);
	len_instance = _update_hook_instance(config.name);
	len_arpa = _update_hook_arpa(config.comm.ip);

	int i;
	for(i=0; i<3; i++)
	{
		uint8_t *head = BUF_O_OFFSET(buf_o_ptr);
		uint8_t *tail = head;
		
		uint16_t id = rand() & 0xffff;
		tail = _serialize_query(tail, id, MDNS_FLAGS_AA, 0, 1, 0, 0);
		tail = _serialize_question(tail, hook_self, MDNS_TYPE_ANY, MDNS_CLASS_INET);
		
		udp_send(config.mdns.socket.sock, BUF_O_BASE(buf_o_ptr), tail-head);

		// wait 250ms second
		uint32_t tick = systick_uptime();
		while(systick_uptime() - tick < SNTP_SYSTICK_RATE / 4)
			;

		//FIXME listen for collisions with hook_self
	}
}
Esempio n. 20
0
static int _tftp_close(tftp_info_t *info)
{
    ebuf_t *buf;
    const char *emsg = "transfer cancelled";	/* some error message */

    if (info->tftp_socket == -1) return 0;

    if (info->tftp_filemode == FILE_MODE_READ) {
	buf = udp_alloc();
	if (buf) {
	    /* If we're on the EOF packet, just send an ack */
	    if (info->tftp_lastblock) {
		ebuf_append_u16_be(buf,TFTP_OP_ACK);
		ebuf_append_u16_be(buf,info->tftp_blknum);
		}
	    else {
		ebuf_append_u16_be(buf,TFTP_OP_ERROR);
		ebuf_append_u16_be(buf,TFTP_ERR_DISKFULL);
		ebuf_append_bytes(buf,emsg,strlen(emsg)+1);
		}
	    udp_send(info->tftp_socket,buf,info->tftp_ipaddr);
	    }
	}
    else {
	/* Just flush out the remaining write data, if any */
	_tftp_writemore(info);
	}

    udp_close(info->tftp_socket);
    info->tftp_socket = -1;
    return 0;
}
Esempio n. 21
0
// Helper function for send/sendto to handle UDP packets.
STATIC mp_uint_t lwip_udp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) {
    if (len > 0xffff) {
        // Any packet that big is probably going to fail the pbuf_alloc anyway, but may as well try
        len = 0xffff;
    }

    // FIXME: maybe PBUF_ROM?
    struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
    if (p == NULL) {
        *_errno = ENOMEM;
        return -1;
    }

    memcpy(p->payload, buf, len);

    err_t err;
    if (ip == NULL) {
        err = udp_send(socket->pcb.udp, p);
    } else {
        ip_addr_t dest;
        IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]);
        err = udp_sendto(socket->pcb.udp, p, &dest, port);
    }

    pbuf_free(p);

    if (err != ERR_OK) {
        *_errno = error_lookup_table[-err];
        return -1;
    }

    return len;
}
Esempio n. 22
0
static void
pxudp_pcb_forward_inbound(struct pxudp *pxudp)
{
    struct pbuf *p;
    u32_t timo;
    err_t error;

    if (!sys_mbox_valid(&pxudp->inmbox)) {
        return;
    }

    timo = sys_mbox_tryfetch(&pxudp->inmbox, (void **)&p);
    if (timo == SYS_MBOX_EMPTY) {
        return;
    }

    error = udp_send(pxudp->pcb, p);
    if (error != ERR_OK) {
        DPRINTF(("%s: udp_send(pcb %p) err %d\n",
                 __func__, (void *)pxudp, error));
    }

    pbuf_free(p);

    /*
     * If we enabled counting in pxudp_pcb_forward_outbound() check
     * that we have (all) the reply(s).
     */
    if (pxudp->count > 0) {
        --pxudp->count;
        if (pxudp->count == 0) {
            pxudp_pcb_expired(pxudp);
        }
    }
}
Esempio n. 23
0
int udp_send_all(int socket, struct in_addr *iface, const struct sockaddr* to, int to_len, int out_len)
{
	struct ifconf	ifc;
	char 		buf[1024] = { 0 };
	struct ifreq	*ifr = 0;
	struct in_addr	from;
	int		i;
	int		rc = 0;
	char		ip[64];

	/* Send through all interfaces */
	ifc.ifc_len = sizeof(buf);
	ifc.ifc_buf = buf;
	ioctl(socket, SIOCGIFCONF, &ifc);
	ifr = ifc.ifc_req;

	for(i=0; i<(ifc.ifc_len/sizeof(*ifr)); i++) {
		from.s_addr = ((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr.s_addr;
		if (iface->s_addr != INADDR_ANY && iface->s_addr != from.s_addr)
			continue;

		if (udp_send(socket, from, to, to_len, out_len) == 1) {
			inet_ntop(AF_INET, &from.s_addr, ip, sizeof(ip));
			wsdd_log(LOG_ERR, "Failed to send udp from %s\n", ip);
			rc = -1;
		}
	}

	return rc;
}
Esempio n. 24
0
/* send one packet (heartbeat) */
int send_packet(void)
{
	static long sequence;
	auto char 	buf[128];
	auto int 	length, retval;

	#GLOBAL_INIT
	{
		sequence = 0;
	}

	/* fill the packet with interesting data (a sequence number) */
	sequence++;
	sprintf(buf, "SEQ=%ld",sequence);
	length = strlen(buf) + 1;

	/* send the packet */
	retval = udp_send(&sock, buf, length);
	if (retval < 0) {
		printf("Error sending datagram!  Closing and reopening socket...\n");
		if (sequence == 1) {
			printf("   (initial ARP request may not have finished)\n");
		}
		sock_close(&sock);
		if(!udp_open(&sock, LOCAL_PORT, resolve(REMOTE_IP), REMOTE_PORT, NULL)) {
			printf("udp_open failed!\n");
			exit(0);
		}
	}

	tcp_tick(NULL);	
	return 1;
}
static int msg_treatment(void)
{
	int err = 0, msg_t = 0, i = 0;
	char path[MAXLEN], *msg;
	msg_st requete;

	MD5_CTX context;
	unsigned char md[MD5_DIGEST_LENGTH];
	char mdascii[2*MD5_DIGEST_LENGTH+1];
	char alert_msg[MAXLEN] = { "" };


	/* receive message from mailbox */
	err = msgrcv(file_id, &requete, sizeof(msg_st),
			     TYPE_DTH_ASYNCH, 0);
	if (err < 0) {
		printf("message can't be received (%s)\n",
		       strerror(err));
		return -1;
	}

	msg = malloc(strlen(addr_interface_s) + MD5_SIZE +
				strlen(requete.message) * sizeof(char));

	/* extract path and message type */
	sscanf(requete.message, "%s %d %254c", path, &msg_t, alert_msg);
	printf("msg received => %s",requete.message);
	if (debug)
		printf("extract path=> %s\nextract message type=>%d\nalert notification=>%s\n", path, msg_t,alert_msg);

	/* compute MD5 */
	MD5_Init(&context);

	MD5_Update(&context, path, strlen(path));

	MD5_Final(md, &context);

	/* Convert raw valure to ascii */
	memset(mdascii, 0, 2*MD5_DIGEST_LENGTH);
	for(i=0; i < MD5_DIGEST_LENGTH; i++)
	{
		sprintf(&(mdascii[i*2]), "%02x", md[i] );
	}

	/* create message */
	sprintf(msg, "%s %s %s %s", addr_interface_s, mdascii, msg_type[msg_t],alert_msg);
	if (debug)
		printf("msg %s\n", msg);

	/*send message */
	if (debug)
		printf("send msg %s\n", msg);
	err = udp_send(msg);
	if (err < 0)
		printf("broadcast error, message can't be send (%s)\n",
		       strerror(err));

	free(msg);
	return 0;
}
Esempio n. 26
0
int main(int argc, char** argv){
    parse_args(argc, argv);
    if(print_usage_flag) {
        print_usage();
        return 0;
    }
    init();
    short accel[3], gyro[3], sensors[1];
    long quat[4];
    unsigned long timestamp;
    unsigned char more[0];
    struct pollfd fdset[1];
    char buf[1];

    // File descriptor for the GPIO interrupt pin
    int gpio_fd = open(GPIO_INT_FILE, O_RDONLY | O_NONBLOCK);

    // Create an event on the GPIO value file
    memset((void*)fdset, 0, sizeof(fdset));
    fdset[0].fd = gpio_fd;
    fdset[0].events = POLLPRI;

    while (1){
        // Blocking poll to wait for an edge on the interrupt
        if(!no_interrupt_flag) {
            poll(fdset, 1, -1);
        }

        if (no_interrupt_flag || fdset[0].revents & POLLPRI) {
            // Read the file to make it reset the interrupt
            if(!no_interrupt_flag) {
                read(fdset[0].fd, buf, 1);
			}

            int fifo_read = dmp_read_fifo(gyro, accel, quat, &timestamp, sensors, more);
            if (fifo_read != 0) {
                //printf("Error reading fifo.\n");
                continue;
            }

            float angles[NOSENTVALS];
            rescale_l(quat, angles+9, QUAT_SCALE, 4);

            // rescale the gyro and accel values received from the IMU from longs that the
            // it uses for efficiency to the floats that they actually are and store these values in the angles array
            rescale_s(gyro, angles+3, GYRO_SCALE, 3);
            rescale_s(accel, angles+6, ACCEL_SCALE, 3);
            // turn the quaternation (that is already in angles) into euler angles and store it in the angles array
            euler(angles+9, angles);
            if(!silent_flag && verbose_flag) {
                printf("Yaw: %+5.1f\tPitch: %+5.1f\tRoll: %+5.1f\n", angles[0]*180.0/PI, angles[1]*180.0/PI, angles[2]*180.0/PI);
            }
            // send the values in angles over UDP as a string (in udp.c/h)
            if(!no_broadcast_flag) {
                udp_send(angles, 13);
            }
        }
    }
}
Esempio n. 27
0
int main() {
    int fd = udp_init_broadcast(8887);
    char *sendtext = "UDP Test\n";
    printf("Sending text:\n%s\n", sendtext);
    udp_send(fd, sendtext, strlen(sendtext));
    udp_close(fd);
    return 0;
}
Esempio n. 28
0
void provSendPacket(const void* buffer, int len)
{
	struct pbuf* p;
	p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
	pbuf_take(p, buffer, len);
	udp_send(eth_udppcb, p);
	pbuf_free(p);
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
	if(argc < 2)
	{
		printf("Usage ./main MD1AC44200003128\n");
		return EXIT_FAILURE;
	}

	int 	prev_value = 100;
	int 	recent_value = 1;
	FILE*	stream;
	char	request[1024], buf[1024], json[1024];

	stream = fopen("config.ini", "r");
	fread(buf, sizeof(char), sizeof(buf), stream);
	fclose(stream);

	printf("Bulb: %s\n", argv[1]);

	while(1)
	{
		sprintf(request, "https://io.adafruit.com/api/feeds/qstation?x-aio-key=%s", buf);
		recent_value = http_request(request);

		if(prev_value != 100 && recent_value != prev_value)
		{
			if(recent_value == 2)
			{
				printf("Turn bulb off.\n");
				sprintf(json, "{\"iswitch\":\"0\",\"r\":\"255\",\"g\":\"255\",\"b\":\"255\",\"bright\":\"20\",\"cmd\":\"light_ctrl\",\"effect\":\"9\",\"sn_list\":[{\"sn\":\"%s\"}]}", argv[1]);
				udp_send(json);
			}
			else if(recent_value == 3)
			{
				printf("Turn bulb on.\n");
				sprintf(json, "{\"iswitch\":\"1\",\"r\":\"255\",\"g\":\"255\",\"b\":\"255\",\"bright\":\"20\",\"cmd\":\"light_ctrl\",\"effect\":\"9\",\"sn_list\":[{\"sn\":\"%s\"}]}", argv[1]);
				udp_send(json);
			}
			else printf("ERROR: Unknown value.\n");
		}

		prev_value = recent_value;
		sleep(10);
	}
	return EXIT_SUCCESS;
}
Esempio n. 30
0
inline
int udp_send(udp_sock& sock, const std::vector<char>& msg)
{
    if(msg.size() == 0)
        return 0;

    return udp_send(sock, &msg[0], msg.size());
}