在iPhone上接收UDP数据包

时间:2010-04-28 14:37:52

标签: iphone sockets udp

我正在尝试通过Wi-Fi在MAC OS和iPod之间建立UDP通信,此时我能够从iPod发送数据包,我可以看到这些数据包具有正确的MAC和IP地址(我正在使用wireshark来监控网络)但MAC仅在wireshark打开时才接收数据包,否则recvfrom()返回-1。

当我尝试从MAC传输到iPhone时,我有相同的结果,我可以看到数据包已发送,但iPhone似乎没有得到它们。

我正在使用下一个代码发送:

 struct addrinfo hints; 
 int rv; 

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

 if ((rv = getaddrinfo(IP, SERVERPORT, &hints, &servinfo)) != 0) { 
  fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); 
  return 1;
 }
 // loop through all the results and make a socket 
 for(p = servinfo; 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 bind socket\n"); 
  return 2;
 }
 while (cond)
  sntBytes += sendto(sockfd, message, strlen(message), 0, p->ai_addr, p->ai_addrlen); 
 return 0;

和此代码接收:

struct addrinfo hints, *p; 
 int rv;

 memset(&hints, 0, sizeof hints); 
 hints.ai_family = AF_UNSPEC; // set 
 hints.ai_socktype = SOCK_DGRAM; 
 hints.ai_flags = AI_PASSIVE; // use to AF_INET to force IPv4 my IP 

 if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
  fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); 
  return 1;
 }
 // loop through all the results and bind to the first we can 
 for(p = servinfo; p != NULL; p = p->ai_next) {
  if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
   perror("listener: socket"); 
   continue;
  }  


  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 socket\n"); 
  return 2;
 } 

 addr_len = sizeof their_addr; 
 fcntl(sockfd, F_SETFL,O_NONBLOCK);

 int rcvbuf_size = 128 * 1024; // That's 128Kb of buffer space.
 setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, 
       &rcvbuf_size, sizeof(rcvbuf_size));

 printf("listener: waiting to recvfrom...\n");

 while (cond)
    rcvBytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len);

return 0;

我错过了什么?

1 个答案:

答案 0 :(得分:1)

获取有关您发送的数据长度的更多信息会很好。 我假设您正在尝试发送ASCII string

此外,这似乎从未被调用过或无限发送循环:

while (cond)
  sntBytes += sendto(sockfd, message, strlen(message), 0, p->ai_addr, p->ai_addrlen);

您可能希望使用实际包含一些错误检查的代码:

发送字符串

int sendResult = send( connectedSocket, stringBuffer, stringLength, 0 );
    if (sendResult == -1)  {
        perror("Error while trying to send string!");
    }
    else {
        NSLog(@"String '%s' sent successfully", stringBuffer );
    }

接收字符串

memset( ReceiveBuffer, '\0', sizeof(ReceiveBuffer) );
    int receiveResult = recv( connectedSocket, ReceiveBuffer, sizeof(ReceiveBuffer), 0);
    if ( receiveResult == -1 ) {
        perror("recv");
    }
    else {
        NSLog(@"String received successfully: '%s'", ReceiveBuffer );
    }