2012-10-24 3 views
2

아이폰에서 보낼 항목을 얻으려고 애 쓰고 있습니다. This Guide 처음에는 프로토콜을 변경하여 UDP 및 TCP에 사용한다고 생각 했으므로 cfSocketRef로 시작했지만 운이 없었습니다. .iOS 6에서 udp 패킷 보내기

다음은 BSD 소켓의 코드입니다. 아무것도 보내는 것 같지 않습니다. localhost : port에서 대기중인 java 소켓 서버가 있습니다.

아이디어가 있으십니까? 또는 작동하는 가이드/샘플 xcode 프로젝트 일 수 있습니다.

#import "ViewController.h" 
    #include <CFNetwork/CFNetwork.h> //temp //dont leave here put it in a header 
    #include <sys/socket.h> 
    #include <netinet/in.h> 
    #include <arpa/inet.h> 

    @interface ViewController() 

    @end 

    @implementation ViewController 


    static void socketCallback(CFSocketRef cfSocket, CFSocketCallBackType 
           type, CFDataRef address, const void *data, void *userInfo) 
    { 
     NSLog(@"socketCallback called"); 
    } 
    // 

    - (void)viewDidLoad 
    { 
     [super viewDidLoad]; 

     int sock = 0; /// ? 
     unsigned int echolen; 

     NSLog(@"starting udp testing"); 
     cfSocketRef = CFSocketCreate(/*CFAllocatorRef allocator*/  NULL, 
            /*SInt32 protocolFamily*/   PF_INET, 
            /*SInt32 socketType*/    SOCK_DGRAM, 
            /*SInt32 protocol*/    IPPROTO_UDP, 
            /*CFOptionFlags callBackTypes*/ kCFSocketAcceptCallBack | kCFSocketDataCallBack, 
            /*CFSocketCallBack callout*/  (CFSocketCallBack)socketCallback, 
            /*const CFSocketContext *context*/ NULL); 



     struct sockaddr_in destination; 
     memset(&destination, 0, sizeof(struct sockaddr_in)); 
     destination.sin_len = sizeof(struct sockaddr_in); 
     destination.sin_family = AF_INET; 

     NSString *ip = @"localhost"; 
     destination.sin_addr.s_addr = inet_addr([ip UTF8String]); 
     destination.sin_port = htons(33033); //port 


     NSString *msg = @"message sent from iPhone"; 
     /* server port */ 
     setsockopt(sock, 
         IPPROTO_IP, 
         IP_MULTICAST_IF, 
         &destination, 
         sizeof(destination)); 

     const char *cmsg = [msg UTF8String]; 

     echolen = strlen(cmsg); 


     if (sendto(sock, 
        cmsg, 
        echolen, 
        0, 
        (struct sockaddr *) &destination, 
        sizeof(destination)) != echolen) 
     { 
      NSLog(@"did send"); 
     } 
     else 
     { 
      NSLog(@"did not send"); 
     } 


    } 





    - (void)didReceiveMemoryWarning 
    { 
     [super didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
    } 

    @end 

답변

3

첫 번째 문제 :

if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { 
    NSLog(@"Failed to create socket, error=%s", strerror(errno)); 
} 

이 제품은 작동하지 않습니다 :

NSString *ip = @"localhost"; 
destination.sin_addr.s_addr = inet_addr([ip UTF8String]); 

inet_addr 같은 점 표기법의 IPv4 주소를 나타내는 문자열을 변환 당신은 소켓을 생성하는 것을 잊었다 "127.0.0.1".

"localhost"와 같은 호스트 이름을 IP 주소로 변환하려면 gethostbyname 또는 getaddrinfo (IPv4 및 IPv6에서 작동 함)을 사용해야합니다.

sendto의 반환 값을 확인하면 다른 오류가 발생합니다. sendto은 성공 사례에서 보낸 바이트 수를 반환하고 오류 경우에는 (-1)을 반환합니다.

if (sendto(sock, ...) == -1) { 
    NSLog(@"did not send, error=%s",strerror(errno)); 
} else { 
    NSLog(@"did send"); 
} 

신속하게 문제를 공개 한 것 errno의 가치를 확인 :처럼 그래서 보일 것입니다.

  • cfSocketRef 전혀 사용되지 않은 : 당신은 소켓을 작성하는 것을 잊지 경우, 오류 메시지가

    가 가 는 보내지 않았다, 비 소켓 오류 = 소켓 작업

    소견

    입니다 귀하의 기능에.
  • 왜 소켓 옵션을 설정합니까? 내가 아는 한 유니 캐스트 메시지에는 필요하지 않으며 멀티 캐스트 메시지에만 필요합니다.
+0

감사합니다 ... 127.0.0.1로 전송됩니다. '오류가 발생합니다.'- 눈에 띄게 다른 것이 있습니까? – Andrew

+1

@Andy : 업데이트 된 답변을 참조하십시오. –

+0

고맙습니다. 일을 끝내고 나서이 기회를 제공 할 것입니다. – Andrew